blob: dcd83c61bf2ff83a3935b1c2fb86a66dd61266ff [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
Eli Friedman39d7c4d2009-05-18 22:50:54 +000014#include "clang/Frontend/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"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000029using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000030using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000031
Chris Lattner77cd2a02007-10-11 00:43:27 +000032namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000033 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000034 enum {
35 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
36 block, ... */
37 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
38 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
39 __block variable */
40 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
41 helpers */
42 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
43 support routines */
44 BLOCK_BYREF_CURRENT_MAX = 256
45 };
46
47 enum {
48 BLOCK_NEEDS_FREE = (1 << 24),
49 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
50 BLOCK_HAS_CXX_OBJ = (1 << 26),
51 BLOCK_IS_GC = (1 << 27),
52 BLOCK_IS_GLOBAL = (1 << 28),
53 BLOCK_HAS_DESCRIPTOR = (1 << 29)
54 };
55
Chris Lattner2c64b7b2007-10-16 21:07:07 +000056 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000057 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000058 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000059 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000060 unsigned TryFinallyContainsReturnDiag;
Mike Stump1eb44332009-09-09 15:08:12 +000061
Chris Lattner01c57482007-10-17 22:35:30 +000062 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000063 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000064 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000065 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000066 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000067 SourceLocation LastIncLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000068
Ted Kremeneka526c5c2008-01-07 19:49:32 +000069 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
70 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
71 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000072 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000073 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
74 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000075 llvm::SmallVector<Stmt *, 32> Stmts;
76 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +000077 // Remember all the @protocol(<expr>) expressions.
78 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000079
80 llvm::DenseSet<uint64_t> CopyDestroyCache;
81
Steve Naroffd82a9ab2008-03-15 00:55:56 +000082 unsigned NumObjCStringLiterals;
Mike Stump1eb44332009-09-09 15:08:12 +000083
Steve Naroffebf2b562007-10-23 23:50:29 +000084 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000085 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000086 FunctionDecl *MsgSendStretFunctionDecl;
87 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000088 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000089 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000090 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000091 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000092 FunctionDecl *CFStringFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000093 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump1eb44332009-09-09 15:08:12 +000094
Steve Naroffbeaf2992007-11-03 11:27:19 +000095 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000096 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000097 RecordDecl *NSStringRecord;
Mike Stump1eb44332009-09-09 15:08:12 +000098
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000099 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000100 int BcLabelCount;
Mike Stump1eb44332009-09-09 15:08:12 +0000101
Steve Naroff874e2322007-11-15 10:28:18 +0000102 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +0000103 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +0000104 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000105 RecordDecl *ConstantStringDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Steve Naroff621edce2009-04-29 16:37:50 +0000107 TypeDecl *ProtocolTypeDecl;
108 QualType getProtocolType();
Mike Stump1eb44332009-09-09 15:08:12 +0000109
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000110 // Needed for header files being rewritten
111 bool IsHeader;
Mike Stump1eb44332009-09-09 15:08:12 +0000112
Steve Naroffa7b402d2008-03-28 22:26:09 +0000113 std::string InFileName;
Eli Friedman66d6f042009-05-18 22:20:00 +0000114 llvm::raw_ostream* OutFile;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000115
116 bool SilenceRewriteMacroWarning;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000117 bool objc_impl_method;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000118
Steve Naroffba92b2e2008-03-27 22:29:16 +0000119 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +0000120
121 // Block expressions.
122 llvm::SmallVector<BlockExpr *, 32> Blocks;
123 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
124 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump1eb44332009-09-09 15:08:12 +0000125
Steve Naroff54055232008-10-27 17:20:55 +0000126 // Block related declarations.
127 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000129 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000130 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
131
132 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
133
Steve Naroffc77a6362008-12-04 16:24:46 +0000134 // This maps a property to it's assignment statement.
135 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000136 // This maps a property to it's synthesied message expression.
137 // This allows us to rewrite chained getters (e.g. o.a.b.c).
138 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump1eb44332009-09-09 15:08:12 +0000139
Steve Naroff4c3580e2008-12-04 23:50:32 +0000140 // This maps an original source AST to it's rewritten form. This allows
141 // us to avoid rewriting the same node twice (which is very uncommon).
142 // This is needed to support some of the exotic property rewriting.
143 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000144
Steve Naroff54055232008-10-27 17:20:55 +0000145 FunctionDecl *CurFunctionDef;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000146 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000147 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000148
Steve Naroffb619d952008-12-09 12:56:34 +0000149 bool DisableReplaceStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000150
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000151 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000152 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000153 virtual void Initialize(ASTContext &context);
154
Chris Lattnerf04da132007-10-24 17:06:59 +0000155 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000156 virtual void HandleTopLevelDecl(DeclGroupRef D) {
157 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
158 HandleTopLevelSingleDecl(*I);
159 }
160 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000161 void HandleDeclInMainFile(Decl *D);
Eli Friedman66d6f042009-05-18 22:20:00 +0000162 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000163 Diagnostic &D, const LangOptions &LOpts,
164 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000165
166 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000167
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000168 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000169
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000170 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000171 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000172
Steve Naroff4c3580e2008-12-04 23:50:32 +0000173 if (ReplacingStmt)
174 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000175
Steve Naroffb619d952008-12-09 12:56:34 +0000176 if (DisableReplaceStmt)
177 return; // Used when rewriting the assignment of a property setter.
178
Steve Naroff4c3580e2008-12-04 23:50:32 +0000179 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000180 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000181 ReplacedNodes[Old] = New;
182 return;
183 }
184 if (SilenceRewriteMacroWarning)
185 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000186 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
187 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000188 }
Steve Naroffb619d952008-12-09 12:56:34 +0000189
190 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
191 // Measaure the old text.
192 int Size = Rewrite.getRangeSize(SrcRange);
193 if (Size == -1) {
194 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
195 << Old->getSourceRange();
196 return;
197 }
198 // Get the new text.
199 std::string SStr;
200 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000201 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000202 const std::string &Str = S.str();
203
204 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000205 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000206 ReplacedNodes[Old] = New;
207 return;
208 }
209 if (SilenceRewriteMacroWarning)
210 return;
211 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
212 << Old->getSourceRange();
213 }
214
Steve Naroffba92b2e2008-03-27 22:29:16 +0000215 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
216 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000217 // If insertion succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000218 if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen),
219 InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000220 SilenceRewriteMacroWarning)
221 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000222
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000223 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
224 }
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Chris Lattneraadaf782008-01-31 19:51:04 +0000226 void RemoveText(SourceLocation Loc, unsigned StrLen) {
227 // If removal succeeded or warning disabled return with no warning.
228 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
229 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000230
Chris Lattneraadaf782008-01-31 19:51:04 +0000231 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
232 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000233
Chris Lattneraadaf782008-01-31 19:51:04 +0000234 void ReplaceText(SourceLocation Start, unsigned OrigLength,
235 const char *NewStr, unsigned NewLength) {
236 // If removal succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000237 if (!Rewrite.ReplaceText(Start, OrigLength,
238 llvm::StringRef(NewStr, NewLength)) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000239 SilenceRewriteMacroWarning)
240 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Chris Lattneraadaf782008-01-31 19:51:04 +0000242 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
243 }
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Chris Lattnerf04da132007-10-24 17:06:59 +0000245 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000246 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000247 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000248 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000249 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000250 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
251 ObjCImplementationDecl *IMD,
252 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000253 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000254 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000255 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000256 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
257 ValueDecl *VD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000258 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
259 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
260 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
261 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000262 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000263 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000264 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000265 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000266 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000267 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000268 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000269 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000270 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000271 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000272
Chris Lattnerf04da132007-10-24 17:06:59 +0000273 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000274 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000275 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Steve Naroff8599e7a2008-12-08 16:43:47 +0000277 Stmt *CurrentBody;
278 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Chris Lattnere64b7772007-10-24 16:57:36 +0000280 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +0000281 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
282 bool &replaced);
283 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Steve Naroffc77a6362008-12-04 16:24:46 +0000284 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump1eb44332009-09-09 15:08:12 +0000285 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000286 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000287 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000288 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000289 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000290 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000291 void WarnAboutReturnGotoStmts(Stmt *S);
292 void HasReturnStmts(Stmt *S, bool &hasReturns);
293 void RewriteTryReturnStmts(Stmt *S);
294 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000295 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000296 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000297 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
298 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
299 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000300 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
301 SourceLocation OrigEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000302 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Steve Naroff934f2762007-10-24 22:48:43 +0000303 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000304 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000305 Stmt *RewriteBreakStmt(BreakStmt *S);
306 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000307 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Steve Naroff09b266e2007-10-30 23:14:51 +0000309 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000310 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000311 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000312 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000313 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000314 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000315 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000316 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000317 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000318
Chris Lattnerf04da132007-10-24 17:06:59 +0000319 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000320 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000321 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000323 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000324 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Douglas Gregor653f1b12009-04-23 01:02:12 +0000326 template<typename MethodIterator>
327 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
328 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000329 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000330 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000331 const char *ClassName,
332 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Steve Naroff621edce2009-04-29 16:37:50 +0000334 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
335 const char *prefix,
336 const char *ClassName,
337 std::string &Result);
338 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump1eb44332009-09-09 15:08:12 +0000339 const char *prefix,
Steve Naroff621edce2009-04-29 16:37:50 +0000340 const char *ClassName,
341 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000342 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000343 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000344 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
345 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000346 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000347 void RewriteImplementations();
348 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000349
Steve Naroff54055232008-10-27 17:20:55 +0000350 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000351 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000352 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000353
Steve Naroff54055232008-10-27 17:20:55 +0000354 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
355 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000356
357 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000358 void RewriteBlockCall(CallExpr *Exp);
359 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000360 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000361 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000362 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Steve Naroff54055232008-10-27 17:20:55 +0000363 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000364
365 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000366 const char *funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000367 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000368 const char *funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000369 std::string SynthesizeBlockImpl(BlockExpr *CE,
370 std::string Tag, std::string Desc);
371 std::string SynthesizeBlockDescriptor(std::string DescTag,
372 std::string ImplTag,
373 int i, const char *funcName,
374 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000375 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000376 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000377 const char *FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000378 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Steve Naroff54055232008-10-27 17:20:55 +0000380 void CollectBlockDeclRefInfo(BlockExpr *Exp);
381 void GetBlockCallExprs(Stmt *S);
382 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Steve Naroff54055232008-10-27 17:20:55 +0000384 // We avoid calling Type::isBlockPointerType(), since it operates on the
385 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000386 bool isTopLevelBlockPointerType(QualType T) {
387 return isa<BlockPointerType>(T);
388 }
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Steve Naroff54055232008-10-27 17:20:55 +0000390 // FIXME: This predicate seems like it would be useful to add to ASTContext.
391 bool isObjCType(QualType T) {
392 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
393 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Steve Naroff54055232008-10-27 17:20:55 +0000395 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Steve Naroff54055232008-10-27 17:20:55 +0000397 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
398 OCT == Context->getCanonicalType(Context->getObjCClassType()))
399 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Ted Kremenek6217b802009-07-29 21:53:49 +0000401 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000402 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000403 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000404 return true;
405 }
406 return false;
407 }
408 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000409 void GetExtentOfArgList(const char *Name, const char *&LParen,
410 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000411 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Steve Narofffa15fd92008-10-28 20:29:00 +0000413 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000414 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Steve Naroff621edce2009-04-29 16:37:50 +0000416 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000417 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000418 if (From[i] == '"')
419 To += "\\\"";
420 else
421 To += From[i];
422 }
423 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000424 };
John McCall9d125032010-01-15 18:39:57 +0000425
426 // Helper function: create a CStyleCastExpr with trivial type source info.
427 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
428 CastExpr::CastKind Kind, Expr *E) {
429 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
430 return new (Ctx) CStyleCastExpr(Ty, Kind, E, TInfo,
431 SourceLocation(), SourceLocation());
432 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000433}
434
Mike Stump1eb44332009-09-09 15:08:12 +0000435void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
436 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000437 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000438 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000439 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000440 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000441 // All the args are checked/rewritten. Don't call twice!
442 RewriteBlockPointerDecl(D);
443 break;
444 }
445 }
446}
447
448void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000449 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000450 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000451 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000452}
453
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000454static bool IsHeaderFile(const std::string &Filename) {
455 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000457 if (DotPos == std::string::npos) {
458 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000459 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000460 }
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000462 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
463 // C header: .h
464 // C++ header: .hh or .H;
465 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000466}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000467
Eli Friedman66d6f042009-05-18 22:20:00 +0000468RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000469 Diagnostic &D, const LangOptions &LOpts,
470 bool silenceMacroWarn)
471 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
472 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000473 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000474 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000475 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000476 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000477 "rewriter doesn't support user-specified control flow semantics "
478 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000479}
480
Eli Friedmanbce831b2009-05-18 22:29:17 +0000481ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
482 llvm::raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000483 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000484 const LangOptions &LOpts,
485 bool SilenceRewriteMacroWarning) {
486 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000487}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000488
Steve Naroffb29b4272008-04-14 22:03:09 +0000489void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000490 Context = &context;
491 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000492 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000493 MsgSendFunctionDecl = 0;
494 MsgSendSuperFunctionDecl = 0;
495 MsgSendStretFunctionDecl = 0;
496 MsgSendSuperStretFunctionDecl = 0;
497 MsgSendFpretFunctionDecl = 0;
498 GetClassFunctionDecl = 0;
499 GetMetaClassFunctionDecl = 0;
500 SelGetUidFunctionDecl = 0;
501 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000502 ConstantStringClassReference = 0;
503 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000504 CurMethodDef = 0;
505 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000506 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000507 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000508 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000509 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000510 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000511 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000512 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000513 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000514 PropParentMap = 0;
515 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000516 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000517 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000519 // Get the ID and start/end of the main file.
520 MainFileID = SM->getMainFileID();
521 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
522 MainFileStart = MainBuf->getBufferStart();
523 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Chris Lattner2c78b872009-04-14 23:22:57 +0000525 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000527 // declaring objc_selector outside the parameter list removes a silly
528 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000529 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000530 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000531 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000532 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000533 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000534 if (LangOpts.Microsoft) {
535 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000536 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
537 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000538 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000539 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000540 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000541 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
542 Preamble += "typedef struct objc_object Protocol;\n";
543 Preamble += "#define _REWRITER_typedef_Protocol\n";
544 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000545 if (LangOpts.Microsoft) {
546 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
547 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
548 } else
549 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
550 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000551 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000552 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000553 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000554 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000555 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000556 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000557 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000558 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000559 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000560 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000561 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000562 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000563 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000564 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
565 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
566 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
567 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
568 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000569 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000570 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000571 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
572 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
573 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000574 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
575 Preamble += "struct __objcFastEnumerationState {\n\t";
576 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000577 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000578 Preamble += "unsigned long *mutationsPtr;\n\t";
579 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000580 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000581 Preamble += "#define __FASTENUMERATIONSTATE\n";
582 Preamble += "#endif\n";
583 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
584 Preamble += "struct __NSConstantStringImpl {\n";
585 Preamble += " int *isa;\n";
586 Preamble += " int flags;\n";
587 Preamble += " char *str;\n";
588 Preamble += " long length;\n";
589 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000590 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
591 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
592 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000593 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000594 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000595 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
596 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000597 // Blocks preamble.
598 Preamble += "#ifndef BLOCK_IMPL\n";
599 Preamble += "#define BLOCK_IMPL\n";
600 Preamble += "struct __block_impl {\n";
601 Preamble += " void *isa;\n";
602 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000603 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000604 Preamble += " void *FuncPtr;\n";
605 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000606 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000607 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000608 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
609 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
610 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
611 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
612 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000613 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
614 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000615 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
616 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
617 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000618 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000619 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000620 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
621 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000622 Preamble += "#define __attribute__(X)\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000623 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000624 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000625 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000626 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000627 Preamble += "#define __weak\n";
628 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000629}
630
631
Chris Lattnerf04da132007-10-24 17:06:59 +0000632//===----------------------------------------------------------------------===//
633// Top Level Driver Code
634//===----------------------------------------------------------------------===//
635
Chris Lattner682bf922009-03-29 16:50:03 +0000636void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000637 // Two cases: either the decl could be in the main file, or it could be in a
638 // #included file. If the former, rewrite it now. If the later, check to see
639 // if we rewrote the #include/#import.
640 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000641 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000642
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000643 // If this is for a builtin, ignore it.
644 if (Loc.isInvalid()) return;
645
Steve Naroffebf2b562007-10-23 23:50:29 +0000646 // Look for built-in declarations that we need to refer during the rewrite.
647 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000648 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000649 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000650 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000651 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000652 ConstantStringClassReference = FVD;
653 return;
654 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000655 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000656 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000657 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000658 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000659 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000660 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000661 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000662 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000663 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000664 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
665 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000666 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
667 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000668 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000669 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000670 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000671 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000672 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000673 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000674}
675
Chris Lattnerf04da132007-10-24 17:06:59 +0000676//===----------------------------------------------------------------------===//
677// Syntactic (non-AST) Rewriting Code
678//===----------------------------------------------------------------------===//
679
Steve Naroffb29b4272008-04-14 22:03:09 +0000680void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000681 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000682 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
683 const char *MainBufStart = MainBuf.first;
684 const char *MainBufEnd = MainBuf.second;
685 size_t ImportLen = strlen("import");
686 size_t IncludeLen = strlen("include");
Mike Stump1eb44332009-09-09 15:08:12 +0000687
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000688 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000689 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
690 if (*BufPtr == '#') {
691 if (++BufPtr == MainBufEnd)
692 return;
693 while (*BufPtr == ' ' || *BufPtr == '\t')
694 if (++BufPtr == MainBufEnd)
695 return;
696 if (!strncmp(BufPtr, "import", ImportLen)) {
697 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000698 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000699 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000700 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000701 BufPtr += ImportLen;
702 }
703 }
704 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000705}
706
Steve Naroffb29b4272008-04-14 22:03:09 +0000707void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000708 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
709 const char *MainBufStart = MainBuf.first;
710 const char *MainBufEnd = MainBuf.second;
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Chris Lattnerf04da132007-10-24 17:06:59 +0000712 // Loop over the whole file, looking for tabs.
713 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
714 if (*BufPtr != '\t')
715 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Chris Lattnerf04da132007-10-24 17:06:59 +0000717 // Okay, we found a tab. This tab will turn into at least one character,
718 // but it depends on which 'virtual column' it is in. Compute that now.
719 unsigned VCol = 0;
720 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
721 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
722 ++VCol;
Mike Stump1eb44332009-09-09 15:08:12 +0000723
Chris Lattnerf04da132007-10-24 17:06:59 +0000724 // Okay, now that we know the virtual column, we know how many spaces to
725 // insert. We assume 8-character tab-stops.
726 unsigned Spaces = 8-(VCol & 7);
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Chris Lattnerf04da132007-10-24 17:06:59 +0000728 // Get the location of the tab.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000729 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
730 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Chris Lattnerf04da132007-10-24 17:06:59 +0000732 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000733 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000734 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000735}
736
Steve Naroffeb0646c2008-12-02 15:48:25 +0000737static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
738 ObjCIvarDecl *OID) {
739 std::string S;
740 S = "((struct ";
741 S += ClassDecl->getIdentifier()->getName();
742 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000743 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000744 return S;
745}
746
Steve Naroffa0876e82008-12-02 17:36:43 +0000747void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
748 ObjCImplementationDecl *IMD,
749 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000750 SourceLocation startLoc = PID->getLocStart();
751 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000752 const char *startBuf = SM->getCharacterData(startLoc);
753 assert((*startBuf == '@') && "bogus @synthesize location");
754 const char *semiBuf = strchr(startBuf, ';');
755 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000756 SourceLocation onePastSemiLoc =
757 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000758
759 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
760 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Steve Naroffeb0646c2008-12-02 15:48:25 +0000762 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000763 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000764 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000765 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000767 if (!OID)
768 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000769
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000770 std::string Getr;
771 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
772 Getr += "{ ";
773 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump1eb44332009-09-09 15:08:12 +0000774 // FIXME: deal with code generation implications for various property
775 // attributes (copy, retain, nonatomic).
Steve Naroff3539cdb2008-12-02 17:54:50 +0000776 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000777 Getr += "return " + getIvarAccessString(ClassDecl, OID);
778 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000779 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000780 if (PD->isReadOnly())
781 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000782
Steve Naroffeb0646c2008-12-02 15:48:25 +0000783 // Generate the 'setter' function.
784 std::string Setr;
785 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000786 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000787 // Synthesize an explicit cast to initialize the ivar.
Mike Stump1eb44332009-09-09 15:08:12 +0000788 // FIXME: deal with code generation implications for various property
789 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000790 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000791 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Narofff4312dc2008-12-11 19:29:16 +0000792 Setr += PD->getNameAsCString();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000793 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000794 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffd40910b2008-12-01 20:33:01 +0000795}
Chris Lattner8a12c272007-10-11 18:38:32 +0000796
Steve Naroffb29b4272008-04-14 22:03:09 +0000797void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000798 // Get the start location and compute the semi location.
799 SourceLocation startLoc = ClassDecl->getLocation();
800 const char *startBuf = SM->getCharacterData(startLoc);
801 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000802
Chris Lattnerf04da132007-10-24 17:06:59 +0000803 // Translate to typedef's that forward reference structs with the same name
804 // as the class. As a convenience, we include the original declaration
805 // as a comment.
806 std::string typedefString;
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000807 typedefString += "// @class ";
808 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
809 I != E; ++I) {
810 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
811 typedefString += ForwardDecl->getNameAsString();
812 if (I+1 != E)
813 typedefString += ", ";
814 else
815 typedefString += ";\n";
816 }
817
Chris Lattner67956052009-02-20 18:04:31 +0000818 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
819 I != E; ++I) {
Ted Kremenek321c22f2009-11-18 00:28:11 +0000820 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff32174822007-11-09 12:50:28 +0000821 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000822 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000823 typedefString += "\n";
824 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000825 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000826 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000827 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000828 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000829 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000830 }
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Steve Naroff934f2762007-10-24 22:48:43 +0000832 // Replace the @class with typedefs corresponding to the classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000833 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattneraadaf782008-01-31 19:51:04 +0000834 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000835}
836
Steve Naroffb29b4272008-04-14 22:03:09 +0000837void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000838 // When method is a synthesized one, such as a getter/setter there is
839 // nothing to rewrite.
840 if (Method->isSynthesized())
841 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000842 SourceLocation LocStart = Method->getLocStart();
843 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000844
Chris Lattner30fc9332009-02-04 01:06:56 +0000845 if (SM->getInstantiationLineNumber(LocEnd) >
846 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000847 InsertText(LocStart, "#if 0\n", 6);
848 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000849 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000850 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000851 }
852}
853
Mike Stump1eb44332009-09-09 15:08:12 +0000854void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000855 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000856
Steve Naroff6327e0d2009-01-11 01:06:09 +0000857 ReplaceText(Loc, 0, "// ", 3);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000858 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000859}
860
Steve Naroffb29b4272008-04-14 22:03:09 +0000861void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000862 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Steve Naroff423cb562007-10-30 13:30:57 +0000864 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000865 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000866
867 for (ObjCCategoryDecl::instmeth_iterator
868 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000869 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000870 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000871 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000872 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000873 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000874 RewriteMethodDeclaration(*I);
875
Steve Naroff423cb562007-10-30 13:30:57 +0000876 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000877 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000878}
879
Steve Naroffb29b4272008-04-14 22:03:09 +0000880void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000881 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump1eb44332009-09-09 15:08:12 +0000882
Steve Naroff752d6ef2007-10-30 16:42:30 +0000883 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000884
Steve Naroff752d6ef2007-10-30 16:42:30 +0000885 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000886 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000887
888 for (ObjCProtocolDecl::instmeth_iterator
889 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000890 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000891 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000892 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000893 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000894 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000895 RewriteMethodDeclaration(*I);
896
Steve Naroff752d6ef2007-10-30 16:42:30 +0000897 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000898 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Chris Lattneraadaf782008-01-31 19:51:04 +0000899 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000900
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000901 // Must comment out @optional/@required
902 const char *startBuf = SM->getCharacterData(LocStart);
903 const char *endBuf = SM->getCharacterData(LocEnd);
904 for (const char *p = startBuf; p < endBuf; p++) {
905 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
906 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000907 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000908 ReplaceText(OptionalLoc, strlen("@optional"),
909 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000910
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000911 }
912 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
913 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000914 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000915 ReplaceText(OptionalLoc, strlen("@required"),
916 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000917
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000918 }
919 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000920}
921
Steve Naroffb29b4272008-04-14 22:03:09 +0000922void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000923 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000924 if (LocStart.isInvalid())
925 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000926 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000927 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000928}
929
Mike Stump1eb44332009-09-09 15:08:12 +0000930void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000931 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000932 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000933 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000934 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000935 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000936 ResultStr += "id";
Steve Narofff4312dc2008-12-11 19:29:16 +0000937 else if (OMD->getResultType()->isFunctionPointerType() ||
938 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000939 // needs special handling, since pointer-to-functions have special
940 // syntax (where a decaration models use).
941 QualType retType = OMD->getResultType();
Steve Narofff4312dc2008-12-11 19:29:16 +0000942 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +0000943 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +0000944 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000945 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +0000946 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +0000947 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Narofff4312dc2008-12-11 19:29:16 +0000948 ResultStr += FPRetType->getResultType().getAsString();
949 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +0000950 }
951 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000952 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000953 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +0000954
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000955 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000956 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000958 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000959 NameStr += "_I_";
960 else
961 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +0000962
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000963 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000964 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +0000965
966 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +0000967 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000968 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000969 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000970 }
Mike Stump1eb44332009-09-09 15:08:12 +0000971 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000972 {
973 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000974 int len = selString.size();
975 for (int i = 0; i < len; i++)
976 if (selString[i] == ':')
977 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000978 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000979 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000980 // Remember this name for metadata emission
981 MethodInternalNames[OMD] = NameStr;
982 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000983
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000984 // Rewrite arguments
985 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000987 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000988 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000989 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000990 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000991 if (!LangOpts.Microsoft) {
992 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
993 ResultStr += "struct ";
994 }
995 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000996 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000997 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000998 }
999 else
Steve Naroff621edce2009-04-29 16:37:50 +00001000 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001002 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001003 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001004 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001005
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001006 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001007 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1008 E = OMD->param_end(); PI != E; ++PI) {
1009 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001010 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001011 if (PDecl->getType()->isObjCQualifiedIdType()) {
1012 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001013 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001014 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001015 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +00001016 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +00001017 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenek6217b802009-07-29 21:53:49 +00001018 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001019 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1020 Context->PrintingPolicy);
Steve Naroffc8ad87b2008-10-30 14:45:29 +00001021 } else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001022 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001023 ResultStr += Name;
1024 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001025 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001026 if (OMD->isVariadic())
1027 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001028 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001029
Steve Naroff76e429d2008-07-16 14:40:40 +00001030 if (FPRetType) {
1031 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001032
Steve Naroff76e429d2008-07-16 14:40:40 +00001033 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001034 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001035 ResultStr += "(";
1036 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1037 if (i) ResultStr += ", ";
1038 std::string ParamStr = FT->getArgType(i).getAsString();
1039 ResultStr += ParamStr;
1040 }
1041 if (FT->isVariadic()) {
1042 if (FT->getNumArgs()) ResultStr += ", ";
1043 ResultStr += "...";
1044 }
1045 ResultStr += ")";
1046 } else {
1047 ResultStr += "()";
1048 }
1049 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001050}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001051void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001052 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1053 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001055 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001056 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001057 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001058 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +00001059
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001060 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001061 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1062 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001063 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001064 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001065 ObjCMethodDecl *OMD = *I;
1066 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001067 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001068 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001069
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001070 const char *startBuf = SM->getCharacterData(LocStart);
1071 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001072 ReplaceText(LocStart, endBuf-startBuf,
1073 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001074 }
Mike Stump1eb44332009-09-09 15:08:12 +00001075
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001076 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001077 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1078 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001079 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001080 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001081 ObjCMethodDecl *OMD = *I;
1082 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001083 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001084 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001085
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001086 const char *startBuf = SM->getCharacterData(LocStart);
1087 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001088 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump1eb44332009-09-09 15:08:12 +00001089 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001090 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001091 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001092 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001093 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001094 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001095 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001096 }
1097
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001098 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001099 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001100 else
Mike Stump1eb44332009-09-09 15:08:12 +00001101 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001102}
1103
Steve Naroffb29b4272008-04-14 22:03:09 +00001104void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001105 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001106 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001107 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001108 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001109 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001110 ResultStr += "\n";
1111 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001112 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001113 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001114 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001115 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001116 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001117 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001118 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001119 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001120 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001121
1122 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001123 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001124 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001125 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001126 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001127 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001128 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001129 for (ObjCInterfaceDecl::classmeth_iterator
1130 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001131 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001132 RewriteMethodDeclaration(*I);
1133
Steve Naroff2feac5e2007-10-30 03:43:13 +00001134 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001135 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001136}
1137
Steve Naroffb619d952008-12-09 12:56:34 +00001138Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1139 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001140 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1141 // This allows us to reuse all the fun and games in SynthMessageExpr().
1142 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1143 ObjCMessageExpr *MsgExpr;
1144 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1145 llvm::SmallVector<Expr *, 1> ExprVec;
1146 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Steve Naroff8599e7a2008-12-08 16:43:47 +00001148 Stmt *Receiver = PropRefExpr->getBase();
1149 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1150 if (PRE && PropGetters[PRE]) {
1151 // This allows us to handle chain/nested property getters.
1152 Receiver = PropGetters[PRE];
1153 }
Mike Stump1eb44332009-09-09 15:08:12 +00001154 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1155 PDecl->getSetterName(), PDecl->getType(),
1156 PDecl->getSetterMethodDecl(),
1157 SourceLocation(), SourceLocation(),
Steve Naroffc77a6362008-12-04 16:24:46 +00001158 &ExprVec[0], 1);
1159 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001160
Steve Naroffc77a6362008-12-04 16:24:46 +00001161 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001162 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001163 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001164 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1165 // to things that stay around.
1166 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001167 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001168}
1169
Steve Naroffc77a6362008-12-04 16:24:46 +00001170Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001171 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1172 // This allows us to reuse all the fun and games in SynthMessageExpr().
1173 ObjCMessageExpr *MsgExpr;
1174 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Steve Naroff8599e7a2008-12-08 16:43:47 +00001176 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00001177
Steve Naroff8599e7a2008-12-08 16:43:47 +00001178 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1179 if (PRE && PropGetters[PRE]) {
1180 // This allows us to handle chain/nested property getters.
1181 Receiver = PropGetters[PRE];
1182 }
Mike Stump1eb44332009-09-09 15:08:12 +00001183 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1184 PDecl->getGetterName(), PDecl->getType(),
1185 PDecl->getGetterMethodDecl(),
1186 SourceLocation(), SourceLocation(),
Steve Naroff15f081d2008-12-03 00:56:33 +00001187 0, 0);
1188
Steve Naroff4c3580e2008-12-04 23:50:32 +00001189 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001190
1191 if (!PropParentMap)
1192 PropParentMap = new ParentMap(CurrentBody);
1193
1194 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1195 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1196 // We stash away the ReplacingStmt since actually doing the
1197 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1198 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001199 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1200 // to things that stay around.
1201 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001202 return PropRefExpr; // return the original...
1203 } else {
1204 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001205 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001206 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1207 // to things that stay around.
1208 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001209 return ReplacingStmt;
1210 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001211}
1212
Mike Stump1eb44332009-09-09 15:08:12 +00001213Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001214 SourceLocation OrigStart,
1215 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001216 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001217 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001218 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001219 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001220 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001221 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001222 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001223 // lookup which class implements the instance variable.
1224 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001225 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001226 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001227 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Steve Narofff0757612008-05-08 17:52:16 +00001229 // Synthesize an explicit cast to gain access to the ivar.
1230 std::string RecName = clsDeclared->getIdentifier()->getName();
1231 RecName += "_IMPL";
1232 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001233 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001234 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001235 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1236 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001237 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1238 CastExpr::CK_Unknown,
1239 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001240 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001241 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1242 IV->getBase()->getLocEnd(),
1243 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001244 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001245 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001246 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001247 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1248 IV->getLocation(),
1249 D->getType());
Steve Naroff4c3580e2008-12-04 23:50:32 +00001250 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001251 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001252 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001253 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001254 // Cannot delete IV->getBase(), since PE points to it.
1255 // Replace the old base with the cast. This is important when doing
1256 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001257 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001258 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001259 }
Steve Naroff84472a82008-04-18 21:55:08 +00001260 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001261 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001262
Steve Naroff9f525972008-05-06 23:20:07 +00001263 // Explicit ivar refs need to have a cast inserted.
1264 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001265 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001266 ObjCInterfaceType *iFaceDecl =
1267 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001268 // lookup which class implements the instance variable.
1269 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001270 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001271 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001272 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001273
Steve Naroff9f525972008-05-06 23:20:07 +00001274 // Synthesize an explicit cast to gain access to the ivar.
1275 std::string RecName = clsDeclared->getIdentifier()->getName();
1276 RecName += "_IMPL";
1277 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001278 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001279 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001280 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1281 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001282 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1283 CastExpr::CK_Unknown,
1284 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001285 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001286 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001287 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001288 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001289 // Cannot delete IV->getBase(), since PE points to it.
1290 // Replace the old base with the cast. This is important when doing
1291 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001292 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001293 return IV;
1294 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001295 }
Steve Naroff84472a82008-04-18 21:55:08 +00001296 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001297}
1298
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001299Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1300 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1301 CI != E; ++CI) {
1302 if (*CI) {
1303 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1304 if (newStmt)
1305 *CI = newStmt;
1306 }
1307 }
1308 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1309 SourceRange OrigStmtRange = S->getSourceRange();
1310 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1311 replaced);
1312 return newStmt;
1313 }
1314 return S;
1315}
1316
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001317/// SynthCountByEnumWithState - To print:
1318/// ((unsigned int (*)
1319/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001320/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001321/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001322/// "countByEnumeratingWithState:objects:count:"),
1323/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001324/// (id *)items, (unsigned int)16)
1325///
Steve Naroffb29b4272008-04-14 22:03:09 +00001326void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001327 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1328 "id *, unsigned int))(void *)objc_msgSend)";
1329 buf += "\n\t\t";
1330 buf += "((id)l_collection,\n\t\t";
1331 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1332 buf += "\n\t\t";
1333 buf += "&enumState, "
1334 "(id *)items, (unsigned int)16)";
1335}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001336
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001337/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1338/// statement to exit to its outer synthesized loop.
1339///
Steve Naroffb29b4272008-04-14 22:03:09 +00001340Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001341 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1342 return S;
1343 // replace break with goto __break_label
1344 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001345
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001346 SourceLocation startLoc = S->getLocStart();
1347 buf = "goto __break_label_";
1348 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001349 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001350
1351 return 0;
1352}
1353
1354/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1355/// statement to continue with its inner synthesized loop.
1356///
Steve Naroffb29b4272008-04-14 22:03:09 +00001357Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001358 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1359 return S;
1360 // replace continue with goto __continue_label
1361 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001362
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001363 SourceLocation startLoc = S->getLocStart();
1364 buf = "goto __continue_label_";
1365 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001366 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001367
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001368 return 0;
1369}
1370
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001371/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001372/// It rewrites:
1373/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001374
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001375/// Into:
1376/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001377/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001378/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001379/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001380/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001381/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001382/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001383/// if (limit) {
1384/// unsigned long startMutations = *enumState.mutationsPtr;
1385/// do {
1386/// unsigned long counter = 0;
1387/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001388/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001389/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001390/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001391/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001392/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001393/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001394/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001395/// objects:items count:16]);
1396/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001397/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001398/// }
1399/// else
1400/// elem = nil;
1401/// }
1402///
Steve Naroffb29b4272008-04-14 22:03:09 +00001403Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001404 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001405 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001406 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001407 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001408 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001409 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001410
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001411 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001412 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001413 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001414 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001415 std::string buf;
1416 buf = "\n{\n\t";
1417 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1418 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001419 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001420 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001421 if (ElementType->isObjCQualifiedIdType() ||
1422 ElementType->isObjCQualifiedInterfaceType())
1423 // Simply use 'id' for all qualified types.
1424 elementTypeAsString = "id";
1425 else
1426 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001427 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001428 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001429 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001430 buf += elementName;
1431 buf += ";\n\t";
1432 }
Chris Lattner06767512008-04-08 05:52:18 +00001433 else {
1434 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001435 elementName = DR->getDecl()->getNameAsCString();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001436 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1437 if (VD->getType()->isObjCQualifiedIdType() ||
1438 VD->getType()->isObjCQualifiedInterfaceType())
1439 // Simply use 'id' for all qualified types.
1440 elementTypeAsString = "id";
1441 else
1442 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001443 }
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001445 // struct __objcFastEnumerationState enumState = { 0 };
1446 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1447 // id items[16];
1448 buf += "id items[16];\n\t";
1449 // id l_collection = (id)
1450 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001451 // Find start location of 'collection' the hard way!
1452 const char *startCollectionBuf = startBuf;
1453 startCollectionBuf += 3; // skip 'for'
1454 startCollectionBuf = strchr(startCollectionBuf, '(');
1455 startCollectionBuf++; // skip '('
1456 // find 'in' and skip it.
1457 while (*startCollectionBuf != ' ' ||
1458 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1459 (*(startCollectionBuf+3) != ' ' &&
1460 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1461 startCollectionBuf++;
1462 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001463
1464 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001465 ReplaceText(startLoc, startCollectionBuf - startBuf,
1466 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001467 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001468 SourceLocation rightParenLoc = S->getRParenLoc();
1469 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1470 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001471 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001472
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001473 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1474 // objects:items count:16];
1475 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001476 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001477 // ((unsigned int (*)
1478 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001479 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001480 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001481 // "countByEnumeratingWithState:objects:count:"),
1482 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001483 // (id *)items, (unsigned int)16);
1484 buf += "unsigned long limit =\n\t\t";
1485 SynthCountByEnumWithState(buf);
1486 buf += ";\n\t";
1487 /// if (limit) {
1488 /// unsigned long startMutations = *enumState.mutationsPtr;
1489 /// do {
1490 /// unsigned long counter = 0;
1491 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001492 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001493 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001494 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001495 buf += "if (limit) {\n\t";
1496 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1497 buf += "do {\n\t\t";
1498 buf += "unsigned long counter = 0;\n\t\t";
1499 buf += "do {\n\t\t\t";
1500 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1501 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1502 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001503 buf += " = (";
1504 buf += elementTypeAsString;
1505 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001506 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001507 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001509 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001510 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001511 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001512 /// objects:items count:16]);
1513 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001514 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001515 /// }
1516 /// else
1517 /// elem = nil;
1518 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001519 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001520 buf = ";\n\t";
1521 buf += "__continue_label_";
1522 buf += utostr(ObjCBcLabelNo.back());
1523 buf += ": ;";
1524 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001525 buf += "} while (counter < limit);\n\t";
1526 buf += "} while (limit = ";
1527 SynthCountByEnumWithState(buf);
1528 buf += ");\n\t";
1529 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001530 buf += " = ((";
1531 buf += elementTypeAsString;
1532 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001533 buf += "__break_label_";
1534 buf += utostr(ObjCBcLabelNo.back());
1535 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001536 buf += "}\n\t";
1537 buf += "else\n\t\t";
1538 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001539 buf += " = ((";
1540 buf += elementTypeAsString;
1541 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001542 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001543
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001544 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001545 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001546 if (isa<CompoundStmt>(S->getBody())) {
1547 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1548 InsertText(endBodyLoc, buf.c_str(), buf.size());
1549 } else {
1550 /* Need to treat single statements specially. For example:
1551 *
1552 * for (A *a in b) if (stuff()) break;
1553 * for (A *a in b) xxxyy;
1554 *
1555 * The following code simply scans ahead to the semi to find the actual end.
1556 */
1557 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1558 const char *semiBuf = strchr(stmtBuf, ';');
1559 assert(semiBuf && "Can't find ';'");
1560 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1561 InsertText(endBodyLoc, buf.c_str(), buf.size());
1562 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001563 Stmts.pop_back();
1564 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001565 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001566}
1567
Mike Stump1eb44332009-09-09 15:08:12 +00001568/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001569/// This routine rewrites @synchronized(expr) stmt;
1570/// into:
1571/// objc_sync_enter(expr);
1572/// @try stmt @finally { objc_sync_exit(expr); }
1573///
Steve Naroffb29b4272008-04-14 22:03:09 +00001574Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001575 // Get the start location and compute the semi location.
1576 SourceLocation startLoc = S->getLocStart();
1577 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001578
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001579 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001580
1581 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001582 buf = "objc_sync_enter((id)";
1583 const char *lparenBuf = startBuf;
1584 while (*lparenBuf != '(') lparenBuf++;
1585 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001586 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1587 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001588 // been rewritten! (which implies the SourceLocation's are invalid).
1589 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001590 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001591 while (*endBuf != ')') endBuf--;
1592 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001593 buf = ");\n";
1594 // declare a new scope with two variables, _stack and _rethrow.
1595 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1596 buf += "int buf[18/*32-bit i386*/];\n";
1597 buf += "char *pointers[4];} _stack;\n";
1598 buf += "id volatile _rethrow = 0;\n";
1599 buf += "objc_exception_try_enter(&_stack);\n";
1600 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001601 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001602 startLoc = S->getSynchBody()->getLocEnd();
1603 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001604
Steve Naroffc7089f12008-08-19 13:04:19 +00001605 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001606 SourceLocation lastCurlyLoc = startLoc;
1607 buf = "}\nelse {\n";
1608 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001609 buf += "}\n";
1610 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001611 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001612
1613 std::string syncBuf;
1614 syncBuf += " objc_sync_exit(";
John McCall9d125032010-01-15 18:39:57 +00001615 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1616 CastExpr::CK_Unknown,
1617 S->getSynchExpr());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001618 std::string syncExprBufS;
1619 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001620 syncExpr->printPretty(syncExprBuf, *Context, 0,
1621 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001622 syncBuf += syncExprBuf.str();
1623 syncBuf += ");";
1624
1625 buf += syncBuf;
1626 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001627 buf += "}\n";
1628 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001629
Chris Lattneraadaf782008-01-31 19:51:04 +00001630 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffb85e77a2009-12-05 21:43:12 +00001631
1632 bool hasReturns = false;
1633 HasReturnStmts(S->getSynchBody(), hasReturns);
1634 if (hasReturns)
1635 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1636
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001637 return 0;
1638}
1639
Steve Naroffb85e77a2009-12-05 21:43:12 +00001640void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1641{
Steve Naroff8c565152008-12-05 17:03:39 +00001642 // Perform a bottom up traversal of all children.
1643 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1644 CI != E; ++CI)
1645 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001646 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001647
Steve Naroffb85e77a2009-12-05 21:43:12 +00001648 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001649 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001650 TryFinallyContainsReturnDiag);
1651 }
1652 return;
1653}
1654
Steve Naroffb85e77a2009-12-05 21:43:12 +00001655void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1656{
1657 // Perform a bottom up traversal of all children.
1658 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1659 CI != E; ++CI)
1660 if (*CI)
1661 HasReturnStmts(*CI, hasReturns);
1662
1663 if (isa<ReturnStmt>(S))
1664 hasReturns = true;
1665 return;
1666}
1667
1668void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1669 // Perform a bottom up traversal of all children.
1670 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1671 CI != E; ++CI)
1672 if (*CI) {
1673 RewriteTryReturnStmts(*CI);
1674 }
1675 if (isa<ReturnStmt>(S)) {
1676 SourceLocation startLoc = S->getLocStart();
1677 const char *startBuf = SM->getCharacterData(startLoc);
1678
1679 const char *semiBuf = strchr(startBuf, ';');
1680 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1681 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1682
1683 std::string buf;
1684 buf = "{ objc_exception_try_exit(&_stack); return";
1685
1686 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1687 InsertText(onePastSemiLoc, "}", 1);
1688 }
1689 return;
1690}
1691
1692void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1693 // Perform a bottom up traversal of all children.
1694 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1695 CI != E; ++CI)
1696 if (*CI) {
1697 RewriteSyncReturnStmts(*CI, syncExitBuf);
1698 }
1699 if (isa<ReturnStmt>(S)) {
1700 SourceLocation startLoc = S->getLocStart();
1701 const char *startBuf = SM->getCharacterData(startLoc);
1702
1703 const char *semiBuf = strchr(startBuf, ';');
1704 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1705 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1706
1707 std::string buf;
1708 buf = "{ objc_exception_try_exit(&_stack);";
1709 buf += syncExitBuf;
1710 buf += " return";
1711
1712 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1713 InsertText(onePastSemiLoc, "}", 1);
1714 }
1715 return;
1716}
1717
Steve Naroffb29b4272008-04-14 22:03:09 +00001718Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001719 // Get the start location and compute the semi location.
1720 SourceLocation startLoc = S->getLocStart();
1721 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001722
Steve Naroff75730982007-11-07 04:08:17 +00001723 assert((*startBuf == '@') && "bogus @try location");
1724
1725 std::string buf;
1726 // declare a new scope with two variables, _stack and _rethrow.
1727 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1728 buf += "int buf[18/*32-bit i386*/];\n";
1729 buf += "char *pointers[4];} _stack;\n";
1730 buf += "id volatile _rethrow = 0;\n";
1731 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001732 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001733
Chris Lattneraadaf782008-01-31 19:51:04 +00001734 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001735
Steve Naroff75730982007-11-07 04:08:17 +00001736 startLoc = S->getTryBody()->getLocEnd();
1737 startBuf = SM->getCharacterData(startLoc);
1738
1739 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001740
Steve Naroff75730982007-11-07 04:08:17 +00001741 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001742 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1743 if (catchList) {
1744 startLoc = startLoc.getFileLocWithOffset(1);
1745 buf = " /* @catch begin */ else {\n";
1746 buf += " id _caught = objc_exception_extract(&_stack);\n";
1747 buf += " objc_exception_try_enter (&_stack);\n";
1748 buf += " if (_setjmp(_stack.buf))\n";
1749 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1750 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001751
Steve Naroffc9ba1722008-07-16 15:31:30 +00001752 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001753 } else { /* no catch list */
1754 buf = "}\nelse {\n";
1755 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1756 buf += "}";
1757 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001758 }
Steve Naroff75730982007-11-07 04:08:17 +00001759 bool sawIdTypedCatch = false;
1760 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001761 while (catchList) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00001762 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001763
Mike Stump1eb44332009-09-09 15:08:12 +00001764 if (catchList == S->getCatchStmts())
Steve Naroff75730982007-11-07 04:08:17 +00001765 buf = "if ("; // we are generating code for the first catch clause
1766 else
1767 buf = "else if (";
1768 startLoc = catchList->getLocStart();
1769 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001770
Steve Naroff75730982007-11-07 04:08:17 +00001771 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001772
Steve Naroff75730982007-11-07 04:08:17 +00001773 const char *lParenLoc = strchr(startBuf, '(');
1774
Steve Naroffbe4b3332008-02-01 22:08:12 +00001775 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001776 // Now rewrite the body...
1777 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001778 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1779 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001780 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1781 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001782 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001783
Steve Naroffe12e6922008-02-01 20:02:07 +00001784 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001785 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001786 } else if (catchDecl) {
1787 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001788 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001789 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001790 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001791 sawIdTypedCatch = true;
Fariborz Jahanian66867c52010-01-12 01:22:23 +00001792 } else if (t->isObjCObjectPointerType()) {
1793 QualType InterfaceTy = t->getPointeeType();
1794 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1795 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroff75730982007-11-07 04:08:17 +00001796 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001797 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001798 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001799 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001800 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001801 }
1802 }
1803 // Now rewrite the body...
1804 lastCatchBody = catchList->getCatchBody();
1805 SourceLocation rParenLoc = catchList->getRParenLoc();
1806 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1807 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1808 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1809 assert((*rParenBuf == ')') && "bogus @catch paren location");
1810 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001811
Steve Naroff75730982007-11-07 04:08:17 +00001812 buf = " = _caught;";
Mike Stump1eb44332009-09-09 15:08:12 +00001813 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001814 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001815 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff7ba138a2009-03-03 19:52:17 +00001816 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001817 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001818 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001819 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001820 catchList = catchList->getNextCatchStmt();
1821 }
1822 // Complete the catch list...
1823 if (lastCatchBody) {
1824 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001825 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1826 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001827
Steve Naroff378f47a2008-09-11 15:29:03 +00001828 // Insert the last (implicit) else clause *before* the right curly brace.
1829 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1830 buf = "} /* last catch end */\n";
1831 buf += "else {\n";
1832 buf += " _rethrow = _caught;\n";
1833 buf += " objc_exception_try_exit(&_stack);\n";
1834 buf += "} } /* @catch end */\n";
1835 if (!S->getFinallyStmt())
1836 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001837 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Steve Naroff75730982007-11-07 04:08:17 +00001839 // Set lastCurlyLoc
1840 lastCurlyLoc = lastCatchBody->getLocEnd();
1841 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001842 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001843 startLoc = finalStmt->getLocStart();
1844 startBuf = SM->getCharacterData(startLoc);
1845 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001846
Steve Naroff75730982007-11-07 04:08:17 +00001847 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001848 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001849
Steve Naroff75730982007-11-07 04:08:17 +00001850 Stmt *body = finalStmt->getFinallyBody();
1851 SourceLocation startLoc = body->getLocStart();
1852 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001853 assert(*SM->getCharacterData(startLoc) == '{' &&
1854 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001855 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001856 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001857
Steve Naroff75730982007-11-07 04:08:17 +00001858 startLoc = startLoc.getFileLocWithOffset(1);
1859 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001860 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001861 endLoc = endLoc.getFileLocWithOffset(-1);
1862 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001863 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Steve Naroff75730982007-11-07 04:08:17 +00001865 // Set lastCurlyLoc
1866 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001867
Steve Naroff8c565152008-12-05 17:03:39 +00001868 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001869 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001870 } else { /* no finally clause - make sure we synthesize an implicit one */
1871 buf = "{ /* implicit finally clause */\n";
1872 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1873 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1874 buf += "}";
1875 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffb85e77a2009-12-05 21:43:12 +00001876
1877 // Now check for any return/continue/go statements within the @try.
1878 // The implicit finally clause won't called if the @try contains any
1879 // jump statements.
1880 bool hasReturns = false;
1881 HasReturnStmts(S->getTryBody(), hasReturns);
1882 if (hasReturns)
1883 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001884 }
1885 // Now emit the final closing curly brace...
1886 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1887 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001888 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001889 return 0;
1890}
1891
Steve Naroffb29b4272008-04-14 22:03:09 +00001892Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001893 return 0;
1894}
1895
Steve Naroffb29b4272008-04-14 22:03:09 +00001896Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001897 return 0;
1898}
1899
Mike Stump1eb44332009-09-09 15:08:12 +00001900// This can't be done with ReplaceStmt(S, ThrowExpr), since
1901// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001902// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001903Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001904 // Get the start location and compute the semi location.
1905 SourceLocation startLoc = S->getLocStart();
1906 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001907
Steve Naroff2bd03922007-11-07 15:32:26 +00001908 assert((*startBuf == '@') && "bogus @throw location");
1909
1910 std::string buf;
1911 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001912 if (S->getThrowExpr())
1913 buf = "objc_exception_throw(";
1914 else // add an implicit argument
1915 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001917 // handle "@ throw" correctly.
1918 const char *wBuf = strchr(startBuf, 'w');
1919 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1920 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001921
Steve Naroff2bd03922007-11-07 15:32:26 +00001922 const char *semiBuf = strchr(startBuf, ';');
1923 assert((*semiBuf == ';') && "@throw: can't find ';'");
1924 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1925 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001926 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001927 return 0;
1928}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001929
Steve Naroffb29b4272008-04-14 22:03:09 +00001930Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001931 // Create a new string expression.
1932 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001933 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001934 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00001935 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1936 StrEncoding.length(), false,StrType,
1937 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001938 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00001939
Chris Lattner07506182007-11-30 22:53:43 +00001940 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001941 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001942 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001943}
1944
Steve Naroffb29b4272008-04-14 22:03:09 +00001945Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00001946 if (!SelGetUidFunctionDecl)
1947 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00001948 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1949 // Create a call to sel_registerName("selName").
1950 llvm::SmallVector<Expr*, 8> SelExprs;
1951 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001952 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00001953 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00001954 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00001955 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00001956 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1957 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001958 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001959 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001960 return SelExp;
1961}
1962
Steve Naroffb29b4272008-04-14 22:03:09 +00001963CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001964 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001965 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001966 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Steve Naroffebf2b562007-10-23 23:50:29 +00001968 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001969 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Steve Naroffebf2b562007-10-23 23:50:29 +00001971 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001972 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump1eb44332009-09-09 15:08:12 +00001973 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001974 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00001975 DRE,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001976 /*isLvalue=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001977
John McCall183700f2009-09-21 23:43:11 +00001978 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Ted Kremenek668bf912009-02-09 20:51:47 +00001980 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1981 SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001982}
1983
Steve Naroffd5255f52007-11-01 13:24:47 +00001984static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1985 const char *&startRef, const char *&endRef) {
1986 while (startBuf < endBuf) {
1987 if (*startBuf == '<')
1988 startRef = startBuf; // mark the start.
1989 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001990 if (startRef && *startRef == '<') {
1991 endRef = startBuf; // mark the end.
1992 return true;
1993 }
1994 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001995 }
1996 startBuf++;
1997 }
1998 return false;
1999}
2000
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002001static void scanToNextArgument(const char *&argRef) {
2002 int angle = 0;
2003 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2004 if (*argRef == '<')
2005 angle++;
2006 else if (*argRef == '>')
2007 angle--;
2008 argRef++;
2009 }
2010 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2011}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002012
Steve Naroffb29b4272008-04-14 22:03:09 +00002013bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002014 if (T->isObjCQualifiedIdType())
2015 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002016 if (const PointerType *PT = T->getAs<PointerType>()) {
2017 if (PT->getPointeeType()->isObjCQualifiedIdType())
2018 return true;
2019 }
2020 if (T->isObjCObjectPointerType()) {
2021 T = T->getPointeeType();
2022 return T->isObjCQualifiedInterfaceType();
2023 }
2024 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002025}
2026
Steve Naroff4f95b752008-07-29 18:15:38 +00002027void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2028 QualType Type = E->getType();
2029 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002030 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002031
Steve Naroffcda658e2008-11-19 21:15:47 +00002032 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2033 Loc = ECE->getLParenLoc();
2034 EndLoc = ECE->getRParenLoc();
2035 } else {
2036 Loc = E->getLocStart();
2037 EndLoc = E->getLocEnd();
2038 }
2039 // This will defend against trying to rewrite synthesized expressions.
2040 if (Loc.isInvalid() || EndLoc.isInvalid())
2041 return;
2042
Steve Naroff4f95b752008-07-29 18:15:38 +00002043 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002044 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002045 const char *startRef = 0, *endRef = 0;
2046 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2047 // Get the locations of the startRef, endRef.
2048 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2049 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2050 // Comment out the protocol references.
2051 InsertText(LessLoc, "/*", 2);
2052 InsertText(GreaterLoc, "*/", 2);
2053 }
2054 }
2055}
2056
Steve Naroffb29b4272008-04-14 22:03:09 +00002057void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002058 SourceLocation Loc;
2059 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002060 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002061 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2062 Loc = VD->getLocation();
2063 Type = VD->getType();
2064 }
2065 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2066 Loc = FD->getLocation();
2067 // Check for ObjC 'id' and class types that have been adorned with protocol
2068 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002069 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002070 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002071 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002072 if (!proto)
2073 return;
2074 Type = proto->getResultType();
2075 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002076 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2077 Loc = FD->getLocation();
2078 Type = FD->getType();
2079 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002080 else
2081 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002082
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002083 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002084 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Steve Naroffd5255f52007-11-01 13:24:47 +00002086 const char *endBuf = SM->getCharacterData(Loc);
2087 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002088 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002089 startBuf--; // scan backward (from the decl location) for return type.
2090 const char *startRef = 0, *endRef = 0;
2091 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2092 // Get the locations of the startRef, endRef.
2093 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2094 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2095 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002096 InsertText(LessLoc, "/*", 2);
2097 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00002098 }
2099 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002100 if (!proto)
2101 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002102 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002103 const char *startBuf = SM->getCharacterData(Loc);
2104 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002105 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2106 if (needToScanForQualifiers(proto->getArgType(i))) {
2107 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002108
Steve Naroffd5255f52007-11-01 13:24:47 +00002109 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002110 // scan forward (from the decl location) for argument types.
2111 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002112 const char *startRef = 0, *endRef = 0;
2113 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2114 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002115 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002116 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002117 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002118 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002119 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002120 InsertText(LessLoc, "/*", 2);
2121 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00002122 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002123 startBuf = ++endBuf;
2124 }
2125 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002126 // If the function name is derived from a macro expansion, then the
2127 // argument buffer will not follow the name. Need to speak with Chris.
2128 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002129 startBuf++; // scan forward (from the decl location) for argument types.
2130 startBuf++;
2131 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002132 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002133}
2134
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002135// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002136void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002137 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2138 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002139 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002140 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002141 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002142 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002143 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002144 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002145 SelGetUidIdent, getFuncType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002146 FunctionDecl::Extern, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002147}
2148
Steve Naroffb29b4272008-04-14 22:03:09 +00002149void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002150 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002151 if (FD->getIdentifier() &&
2152 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002153 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002154 return;
2155 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002156 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002157}
2158
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002159void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2160 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2161 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2162 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2163 if (!proto)
2164 return;
2165 QualType Type = proto->getResultType();
2166 std::string FdStr = Type.getAsString();
2167 FdStr += " ";
2168 FdStr += FD->getNameAsCString();
2169 FdStr += "(";
2170 unsigned numArgs = proto->getNumArgs();
2171 for (unsigned i = 0; i < numArgs; i++) {
2172 QualType ArgType = proto->getArgType(i);
2173 FdStr += ArgType.getAsString();
2174
2175 if (i+1 < numArgs)
2176 FdStr += ", ";
2177 }
2178 FdStr += ");\n";
2179 InsertText(FunLocStart, FdStr.c_str(), FdStr.size());
2180 CurFunctionDeclToDeclareForBlock = 0;
2181}
2182
Steve Naroffc0a123c2008-03-11 17:37:02 +00002183// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002184void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002185 if (SuperContructorFunctionDecl)
2186 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002187 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002188 llvm::SmallVector<QualType, 16> ArgTys;
2189 QualType argT = Context->getObjCIdType();
2190 assert(!argT.isNull() && "Can't find 'id' type");
2191 ArgTys.push_back(argT);
2192 ArgTys.push_back(argT);
2193 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2194 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002195 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002196 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002197 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002198 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002199 FunctionDecl::Extern, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002200}
2201
Steve Naroff09b266e2007-10-30 23:14:51 +00002202// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002203void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002204 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2205 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002206 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002207 assert(!argT.isNull() && "Can't find 'id' type");
2208 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002209 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002210 assert(!argT.isNull() && "Can't find 'SEL' type");
2211 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002212 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002213 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002214 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002215 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002216 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002217 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002218 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002219}
2220
Steve Naroff874e2322007-11-15 10:28:18 +00002221// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002222void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002223 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2224 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002225 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002226 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002227 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002228 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2229 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2230 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002231 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002232 assert(!argT.isNull() && "Can't find 'SEL' type");
2233 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002234 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002235 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002236 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002237 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002238 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002239 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002240 FunctionDecl::Extern, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002241}
2242
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002243// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002244void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002245 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2246 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002247 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002248 assert(!argT.isNull() && "Can't find 'id' type");
2249 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002250 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002251 assert(!argT.isNull() && "Can't find 'SEL' type");
2252 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002253 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002254 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002255 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002256 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002257 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002258 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002259 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002260}
2261
Mike Stump1eb44332009-09-09 15:08:12 +00002262// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002263// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002264void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002265 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002266 &Context->Idents.get("objc_msgSendSuper_stret");
2267 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002268 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002269 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002270 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002271 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2272 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2273 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002274 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002275 assert(!argT.isNull() && "Can't find 'SEL' type");
2276 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002277 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002278 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002279 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002280 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002281 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002282 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002283 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002284}
2285
Steve Naroff1284db82008-05-08 22:02:18 +00002286// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002287void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002288 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2289 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002290 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002291 assert(!argT.isNull() && "Can't find 'id' type");
2292 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002293 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002294 assert(!argT.isNull() && "Can't find 'SEL' type");
2295 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002296 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002297 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002298 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002299 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002300 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002301 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002302 FunctionDecl::Extern, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002303}
2304
Steve Naroff09b266e2007-10-30 23:14:51 +00002305// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002306void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002307 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2308 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002309 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002310 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002311 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002312 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002313 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002314 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002315 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002316 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002317}
2318
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002319// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002320void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002321 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2322 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002323 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002324 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002325 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002326 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002327 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002328 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002329 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002330 FunctionDecl::Extern, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002331}
2332
Steve Naroffb29b4272008-04-14 22:03:09 +00002333Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002334 QualType strType = getConstantStringStructType();
2335
2336 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002337
2338 std::string tmpName = InFileName;
2339 unsigned i;
2340 for (i=0; i < tmpName.length(); i++) {
2341 char c = tmpName.at(i);
2342 // replace any non alphanumeric characters with '_'.
2343 if (!isalpha(c) && (c < '0' || c > '9'))
2344 tmpName[i] = '_';
2345 }
2346 S += tmpName;
2347 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002348 S += utostr(NumObjCStringLiterals++);
2349
Steve Naroffba92b2e2008-03-27 22:29:16 +00002350 Preamble += "static __NSConstantStringImpl " + S;
2351 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2352 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002353 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002354 std::string prettyBufS;
2355 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002356 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2357 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002358 Preamble += prettyBuf.str();
2359 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002360 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002361
2362 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2363 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002364 VarDecl::Static);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002365 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2366 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002367 Context->getPointerType(DRE->getType()),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002368 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002369 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002370 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2371 CastExpr::CK_Unknown, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002372 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002373 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002374 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002375}
2376
Steve Naroffb29b4272008-04-14 22:03:09 +00002377ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002378 // check if we are sending a message to 'super'
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002379 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002380
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002381 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002382 const ObjCObjectPointerType *OPT =
John McCall183700f2009-09-21 23:43:11 +00002383 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00002384 assert(OPT);
2385 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002386 return IT->getDecl();
2387 }
2388 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002389}
2390
2391// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002392QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002393 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002394 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002395 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002396 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002397 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002398
Steve Naroff874e2322007-11-15 10:28:18 +00002399 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002400 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002401 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002402 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002403
Steve Naroff874e2322007-11-15 10:28:18 +00002404 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002405 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002406 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2407 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002408 FieldTypes[i], 0,
2409 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002410 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002411 }
Mike Stump1eb44332009-09-09 15:08:12 +00002412
Douglas Gregor44b43212008-12-11 16:49:14 +00002413 SuperStructDecl->completeDefinition(*Context);
Steve Naroff874e2322007-11-15 10:28:18 +00002414 }
2415 return Context->getTagDeclType(SuperStructDecl);
2416}
2417
Steve Naroffb29b4272008-04-14 22:03:09 +00002418QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002419 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002420 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002421 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002422 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002423 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002424
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002425 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002426 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002427 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002428 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002429 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002430 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002431 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002432 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002433
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002434 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002435 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002436 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2437 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002438 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002439 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002440 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002441 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002442 }
2443
2444 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002445 }
2446 return Context->getTagDeclType(ConstantStringDecl);
2447}
2448
Steve Naroffb29b4272008-04-14 22:03:09 +00002449Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002450 if (!SelGetUidFunctionDecl)
2451 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002452 if (!MsgSendFunctionDecl)
2453 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002454 if (!MsgSendSuperFunctionDecl)
2455 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002456 if (!MsgSendStretFunctionDecl)
2457 SynthMsgSendStretFunctionDecl();
2458 if (!MsgSendSuperStretFunctionDecl)
2459 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002460 if (!MsgSendFpretFunctionDecl)
2461 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002462 if (!GetClassFunctionDecl)
2463 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002464 if (!GetMetaClassFunctionDecl)
2465 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002466
Steve Naroff874e2322007-11-15 10:28:18 +00002467 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002468 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2469 // May need to use objc_msgSend_stret() as well.
2470 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002471 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2472 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002473 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002474 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002475 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002476 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002477 }
Mike Stump1eb44332009-09-09 15:08:12 +00002478
Steve Naroff934f2762007-10-24 22:48:43 +00002479 // Synthesize a call to objc_msgSend().
2480 llvm::SmallVector<Expr*, 8> MsgExprs;
2481 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump1eb44332009-09-09 15:08:12 +00002482
Steve Naroff934f2762007-10-24 22:48:43 +00002483 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2484 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002485 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2486 // the 'super' idiom within a class method.
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00002487 if (clsName->getName() == "super") {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002488 MsgSendFlavor = MsgSendSuperFunctionDecl;
2489 if (MsgSendStretFlavor)
2490 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2491 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002492
2493 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002494 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002495
2496 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002497
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002498 // set the receiver to self, the first argument to all methods.
Steve Naroff621edce2009-04-29 16:37:50 +00002499 InitExprs.push_back(
John McCall9d125032010-01-15 18:39:57 +00002500 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2501 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002502 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff621edce2009-04-29 16:37:50 +00002503 Context->getObjCIdType(),
John McCall9d125032010-01-15 18:39:57 +00002504 SourceLocation()))
2505 ); // set the 'receiver'.
Steve Naroff621edce2009-04-29 16:37:50 +00002506
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002507 llvm::SmallVector<Expr*, 8> ClsExprs;
2508 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002509 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002510 SuperDecl->getIdentifier()->getNameStart(),
2511 SuperDecl->getIdentifier()->getLength(),
2512 false, argType, SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002513 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002514 &ClsExprs[0],
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002515 ClsExprs.size());
2516 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002517 InitExprs.push_back( // set 'super class', using objc_getClass().
John McCall9d125032010-01-15 18:39:57 +00002518 NoTypeInfoCStyleCastExpr(Context,
2519 Context->getObjCIdType(),
2520 CastExpr::CK_Unknown, Cls));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002521 // struct objc_super
2522 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002523 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002524
Steve Naroff23f41272008-03-11 18:14:26 +00002525 if (LangOpts.Microsoft) {
2526 SynthSuperContructorFunctionDecl();
2527 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002528 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff23f41272008-03-11 18:14:26 +00002529 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002530 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002531 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002532 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002533 // The code for super is a little tricky to prevent collision with
2534 // the structure definition in the header. The rewriter has it's own
2535 // internal definition (__rw_objc_super) that is uses. This is why
2536 // we need the cast below. For example:
2537 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2538 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002539 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002540 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002541 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00002542 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2543 Context->getPointerType(superType),
2544 CastExpr::CK_Unknown, SuperRep);
Mike Stump1eb44332009-09-09 15:08:12 +00002545 } else {
Steve Naroff23f41272008-03-11 18:14:26 +00002546 // (struct objc_super) { <exprs from above> }
Mike Stump1eb44332009-09-09 15:08:12 +00002547 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2548 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002549 SourceLocation());
John McCall42f56b52010-01-18 19:35:47 +00002550 TypeSourceInfo *superTInfo
2551 = Context->getTrivialTypeSourceInfo(superType);
John McCall1d7d8d62010-01-19 22:33:45 +00002552 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2553 superType, ILE, false);
Steve Naroff46a98a72008-12-23 20:11:22 +00002554 // struct objc_super *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002555 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002556 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002557 SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002558 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002559 MsgExprs.push_back(SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002560 } else {
2561 llvm::SmallVector<Expr*, 8> ClsExprs;
2562 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002563 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002564 clsName->getNameStart(),
Chris Lattner2085fd62009-02-18 06:40:38 +00002565 clsName->getLength(),
2566 false, argType,
2567 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002568 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002569 &ClsExprs[0],
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002570 ClsExprs.size());
2571 MsgExprs.push_back(Cls);
2572 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002573 } else { // instance message.
2574 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002575
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002576 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002577 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002578 if (MsgSendStretFlavor)
2579 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002580 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002581
Steve Naroff874e2322007-11-15 10:28:18 +00002582 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002583
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002584 InitExprs.push_back(
John McCall9d125032010-01-15 18:39:57 +00002585 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2586 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002587 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002588 Context->getObjCIdType(),
John McCall9d125032010-01-15 18:39:57 +00002589 SourceLocation()))
2590 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002591
Steve Naroff874e2322007-11-15 10:28:18 +00002592 llvm::SmallVector<Expr*, 8> ClsExprs;
2593 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002594 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002595 SuperDecl->getIdentifier()->getNameStart(),
2596 SuperDecl->getIdentifier()->getLength(),
2597 false, argType, SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002598 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002599 &ClsExprs[0],
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002600 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002601 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002602 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002603 // set 'super class', using objc_getClass().
John McCall9d125032010-01-15 18:39:57 +00002604 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2605 CastExpr::CK_Unknown, Cls));
Steve Naroff874e2322007-11-15 10:28:18 +00002606 // struct objc_super
2607 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002608 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002609
Steve Naroffc0a123c2008-03-11 17:37:02 +00002610 if (LangOpts.Microsoft) {
2611 SynthSuperContructorFunctionDecl();
2612 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002613 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffc0a123c2008-03-11 17:37:02 +00002614 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002615 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002616 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002617 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002618 // The code for super is a little tricky to prevent collision with
2619 // the structure definition in the header. The rewriter has it's own
2620 // internal definition (__rw_objc_super) that is uses. This is why
2621 // we need the cast below. For example:
2622 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2623 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002624 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002625 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002626 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00002627 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2628 Context->getPointerType(superType),
2629 CastExpr::CK_Unknown, SuperRep);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002630 } else {
2631 // (struct objc_super) { <exprs from above> }
Mike Stump1eb44332009-09-09 15:08:12 +00002632 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2633 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002634 SourceLocation());
John McCall42f56b52010-01-18 19:35:47 +00002635 TypeSourceInfo *superTInfo
2636 = Context->getTrivialTypeSourceInfo(superType);
John McCall1d7d8d62010-01-19 22:33:45 +00002637 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2638 superType, ILE, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002639 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002640 MsgExprs.push_back(SuperRep);
Steve Naroff874e2322007-11-15 10:28:18 +00002641 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002642 // Remove all type-casts because it may contain objc-style types; e.g.
2643 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002644 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002645 recExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00002646 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2647 CastExpr::CK_Unknown, recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +00002648 MsgExprs.push_back(recExpr);
2649 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002650 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002651 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002652 llvm::SmallVector<Expr*, 8> SelExprs;
2653 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002654 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002655 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002656 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002657 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002658 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2659 &SelExprs[0], SelExprs.size());
2660 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002661
Steve Naroff934f2762007-10-24 22:48:43 +00002662 // Now push any user supplied arguments.
2663 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002664 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002665 // Make all implicit casts explicit...ICE comes in handy:-)
2666 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2667 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002668 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002669 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002670 : ICE->getType();
John McCall9d125032010-01-15 18:39:57 +00002671 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown,
2672 userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002673 }
2674 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002675 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002676 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002677 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002678 userExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00002679 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2680 CastExpr::CK_Unknown, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002681 }
Mike Stump1eb44332009-09-09 15:08:12 +00002682 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002683 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002684 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2685 // out the argument in the original expression (since we aren't deleting
2686 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2687 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002688 }
Steve Naroffab972d32007-11-04 22:37:50 +00002689 // Generate the funky cast.
2690 CastExpr *cast;
2691 llvm::SmallVector<QualType, 8> ArgTypes;
2692 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002693
Steve Naroffab972d32007-11-04 22:37:50 +00002694 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002695 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2696 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2697 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002698 ArgTypes.push_back(Context->getObjCIdType());
2699 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002700 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002701 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002702 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2703 E = OMD->param_end(); PI != E; ++PI) {
2704 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002705 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002706 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002707 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002708 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002709 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffa206b062008-10-29 14:49:46 +00002710 t = Context->getPointerType(BPT->getPointeeType());
2711 }
Steve Naroff352336b2007-11-05 14:36:37 +00002712 ArgTypes.push_back(t);
2713 }
Chris Lattner89951a82009-02-20 18:43:26 +00002714 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2715 ? Context->getObjCIdType() : OMD->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002716 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002717 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002718 }
2719 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002720 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002721
Steve Naroffab972d32007-11-04 22:37:50 +00002722 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002723 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002724 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002725
Mike Stump1eb44332009-09-09 15:08:12 +00002726 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002727 // If we don't do this cast, we get the following bizarre warning/note:
2728 // xx.m:13: warning: function called through a non-compatible type
2729 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00002730 cast = NoTypeInfoCStyleCastExpr(Context,
2731 Context->getPointerType(Context->VoidTy),
2732 CastExpr::CK_Unknown, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00002733
Steve Naroffab972d32007-11-04 22:37:50 +00002734 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002735 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002736 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002737 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002738 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002739 castType = Context->getPointerType(castType);
John McCall9d125032010-01-15 18:39:57 +00002740 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2741 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00002742
2743 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002744 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002745
John McCall183700f2009-09-21 23:43:11 +00002746 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002747 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002748 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002749 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002750 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002751 if (MsgSendStretFlavor) {
2752 // We have the method which returns a struct/union. Must also generate
2753 // call to objc_msgSend_stret and hang both varieties on a conditional
2754 // expression which dictate which one to envoke depending on size of
2755 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00002756
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002757 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002758 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002759 SourceLocation());
2760 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00002761 cast = NoTypeInfoCStyleCastExpr(Context,
2762 Context->getPointerType(Context->VoidTy),
2763 CastExpr::CK_Unknown, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002764 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002765 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002766 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002767 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002768 castType = Context->getPointerType(castType);
John McCall9d125032010-01-15 18:39:57 +00002769 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2770 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002771
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002772 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002773 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002774
John McCall183700f2009-09-21 23:43:11 +00002775 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002776 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002777 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002778 FT->getResultType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002779
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002780 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00002781 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00002782 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00002783 Context->getSizeType(),
2784 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002785 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2786 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2787 // For X86 it is more complicated and some kind of target specific routine
2788 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00002789 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00002790 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump1eb44332009-09-09 15:08:12 +00002791 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002792 Context->IntTy,
2793 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002794 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2795 BinaryOperator::LE,
2796 Context->IntTy,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002797 SourceLocation());
2798 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00002799 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00002800 new (Context) ConditionalOperator(lessThanExpr,
2801 SourceLocation(), CE,
2802 SourceLocation(), STCE, returnType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002803 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002804 }
Mike Stump1eb44332009-09-09 15:08:12 +00002805 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002806 return ReplacingStmt;
2807}
2808
Steve Naroffb29b4272008-04-14 22:03:09 +00002809Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002810 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00002811
Steve Naroff934f2762007-10-24 22:48:43 +00002812 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002813 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00002814
2815 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002816 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002817}
2818
Steve Naroff621edce2009-04-29 16:37:50 +00002819// typedef struct objc_object Protocol;
2820QualType RewriteObjC::getProtocolType() {
2821 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00002822 TypeSourceInfo *TInfo
2823 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00002824 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002825 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00002826 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00002827 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00002828 }
2829 return Context->getTypeDeclType(ProtocolTypeDecl);
2830}
2831
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002832/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00002833/// a synthesized/forward data reference (to the protocol's metadata).
2834/// The forward references (and metadata) are generated in
2835/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00002836Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00002837 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2838 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00002839 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor0da76df2009-11-23 11:41:28 +00002840 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroff621edce2009-04-29 16:37:50 +00002841 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2842 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2843 Context->getPointerType(DRE->getType()),
2844 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00002845 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
2846 CastExpr::CK_Unknown,
2847 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002848 ReplaceStmt(Exp, castExpr);
2849 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump1eb44332009-09-09 15:08:12 +00002850 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00002851 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002852
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002853}
2854
Mike Stump1eb44332009-09-09 15:08:12 +00002855bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00002856 const char *endBuf) {
2857 while (startBuf < endBuf) {
2858 if (*startBuf == '#') {
2859 // Skip whitespace.
2860 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2861 ;
2862 if (!strncmp(startBuf, "if", strlen("if")) ||
2863 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2864 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2865 !strncmp(startBuf, "define", strlen("define")) ||
2866 !strncmp(startBuf, "undef", strlen("undef")) ||
2867 !strncmp(startBuf, "else", strlen("else")) ||
2868 !strncmp(startBuf, "elif", strlen("elif")) ||
2869 !strncmp(startBuf, "endif", strlen("endif")) ||
2870 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2871 !strncmp(startBuf, "include", strlen("include")) ||
2872 !strncmp(startBuf, "import", strlen("import")) ||
2873 !strncmp(startBuf, "include_next", strlen("include_next")))
2874 return true;
2875 }
2876 startBuf++;
2877 }
2878 return false;
2879}
2880
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002881/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002882/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002883void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002884 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002885 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump1eb44332009-09-09 15:08:12 +00002886 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002887 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002888 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002889 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002890 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002891 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002892 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002893 SourceLocation LocStart = CDecl->getLocStart();
2894 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002895
Steve Narofffea763e82007-11-14 19:25:57 +00002896 const char *startBuf = SM->getCharacterData(LocStart);
2897 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00002898
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002899 // If no ivars and no root or if its root, directly or indirectly,
2900 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002901 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2902 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00002903 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattneraadaf782008-01-31 19:51:04 +00002904 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002905 return;
2906 }
Mike Stump1eb44332009-09-09 15:08:12 +00002907
2908 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002909 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002910 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002911 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002912 if (LangOpts.Microsoft)
2913 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002914
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002915 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002916 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00002917 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002918 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002919 // If the buffer contains preprocessor directives, we do more fine-grained
2920 // rewrites. This is intended to fix code that looks like (which occurs in
2921 // NSURL.h, for example):
2922 //
2923 // #ifdef XYZ
2924 // @interface Foo : NSObject
2925 // #else
2926 // @interface FooBar : NSObject
2927 // #endif
2928 // {
2929 // int i;
2930 // }
2931 // @end
2932 //
2933 // This clause is segregated to avoid breaking the common case.
2934 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002935 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00002936 CDecl->getClassLoc();
2937 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00002938 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002939
Chris Lattnercafeb352009-02-20 18:18:36 +00002940 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002941 // advance to the end of the referenced protocols.
2942 while (endHeader < cursor && *endHeader != '>') endHeader++;
2943 endHeader++;
2944 }
2945 // rewrite the original header
2946 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2947 } else {
2948 // rewrite the original header *without* disturbing the '{'
Steve Naroff17c87782009-12-04 21:36:32 +00002949 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffbaf58c32008-05-31 14:15:04 +00002950 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002951 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002952 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002953 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002954 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002955 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002956 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002957
Steve Narofffea763e82007-11-14 19:25:57 +00002958 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002959 SourceLocation OnePastCurly =
2960 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2961 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002962 }
2963 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00002964
Steve Narofffea763e82007-11-14 19:25:57 +00002965 // Now comment out any visibility specifiers.
2966 while (cursor < endBuf) {
2967 if (*cursor == '@') {
2968 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002969 // Skip whitespace.
2970 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2971 /*scan*/;
2972
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002973 // FIXME: presence of @public, etc. inside comment results in
2974 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002975 if (!strncmp(cursor, "public", strlen("public")) ||
2976 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002977 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002978 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002979 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002980 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002981 // FIXME: If there are cases where '<' is used in ivar declaration part
2982 // of user code, then scan the ivar list and use needToScanForQualifiers
2983 // for type checking.
2984 else if (*cursor == '<') {
2985 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002986 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002987 cursor = strchr(cursor, '>');
2988 cursor++;
2989 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002990 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002991 } else if (*cursor == '^') { // rewrite block specifier.
2992 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2993 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002994 }
Steve Narofffea763e82007-11-14 19:25:57 +00002995 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002996 }
Steve Narofffea763e82007-11-14 19:25:57 +00002997 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002998 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002999 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003000 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003001 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003002 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003003 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003004 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003005 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00003006 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003007 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003008 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003009 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003010 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003011}
3012
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003013// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003014/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003015template<typename MethodIterator>
3016void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3017 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003018 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003019 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00003020 const char *ClassName,
3021 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003022 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003023
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003024 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003025 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003026 SEL _cmd;
3027 char *method_types;
3028 void *_imp;
3029 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003030 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003031 Result += "\nstruct _objc_method {\n";
3032 Result += "\tSEL _cmd;\n";
3033 Result += "\tchar *method_types;\n";
3034 Result += "\tvoid *_imp;\n";
3035 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003036
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003037 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003038 }
Mike Stump1eb44332009-09-09 15:08:12 +00003039
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003040 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003041
Steve Naroff946a6932008-03-11 00:12:29 +00003042 /* struct {
3043 struct _objc_method_list *next_method;
3044 int method_count;
3045 struct _objc_method method_list[];
3046 }
3047 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003048 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003049 Result += "\nstatic struct {\n";
3050 Result += "\tstruct _objc_method_list *next_method;\n";
3051 Result += "\tint method_count;\n";
3052 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003053 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003054 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003055 Result += prefix;
3056 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3057 Result += "_METHODS_";
3058 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003059 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003060 Result += IsInstanceMethod ? "inst" : "cls";
3061 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003062 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003063
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003064 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003065 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003066 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003067 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003068 Result += "\", \"";
3069 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003070 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003071 Result += MethodInternalNames[*MethodBegin];
3072 Result += "}\n";
3073 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3074 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003075 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003076 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003077 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003078 Result += "\", \"";
3079 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003080 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003081 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003082 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003083 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003084 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003085}
3086
Steve Naroff621edce2009-04-29 16:37:50 +00003087/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003088void RewriteObjC::
Steve Naroff621edce2009-04-29 16:37:50 +00003089RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3090 const char *ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003091 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003092
3093 // Output struct protocol_methods holder of method selector and type.
3094 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3095 /* struct protocol_methods {
3096 SEL _cmd;
3097 char *method_types;
3098 }
3099 */
3100 Result += "\nstruct _protocol_methods {\n";
3101 Result += "\tstruct objc_selector *_cmd;\n";
3102 Result += "\tchar *method_types;\n";
3103 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003104
Steve Naroff621edce2009-04-29 16:37:50 +00003105 objc_protocol_methods = true;
3106 }
3107 // Do not synthesize the protocol more than once.
3108 if (ObjCSynthesizedProtocols.count(PDecl))
3109 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003110
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003111 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3112 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3113 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003114 /* struct _objc_protocol_method_list {
3115 int protocol_method_count;
3116 struct protocol_methods protocols[];
3117 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003118 */
Steve Naroff621edce2009-04-29 16:37:50 +00003119 Result += "\nstatic struct {\n";
3120 Result += "\tint protocol_method_count;\n";
3121 Result += "\tstruct _protocol_methods protocol_methods[";
3122 Result += utostr(NumMethods);
3123 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3124 Result += PDecl->getNameAsString();
3125 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3126 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003127
Steve Naroff621edce2009-04-29 16:37:50 +00003128 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003129 for (ObjCProtocolDecl::instmeth_iterator
3130 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003131 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003132 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003133 Result += "\t ,{{(struct objc_selector *)\"";
3134 else
3135 Result += "\t ,{(struct objc_selector *)\"";
3136 Result += (*I)->getSelector().getAsString().c_str();
3137 std::string MethodTypeString;
3138 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3139 Result += "\", \"";
3140 Result += MethodTypeString;
3141 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003142 }
Steve Naroff621edce2009-04-29 16:37:50 +00003143 Result += "\t }\n};\n";
3144 }
Mike Stump1eb44332009-09-09 15:08:12 +00003145
Steve Naroff621edce2009-04-29 16:37:50 +00003146 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003147 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3148 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003149 if (NumMethods > 0) {
3150 /* struct _objc_protocol_method_list {
3151 int protocol_method_count;
3152 struct protocol_methods protocols[];
3153 }
3154 */
3155 Result += "\nstatic struct {\n";
3156 Result += "\tint protocol_method_count;\n";
3157 Result += "\tstruct _protocol_methods protocol_methods[";
3158 Result += utostr(NumMethods);
3159 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3160 Result += PDecl->getNameAsString();
3161 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3162 "{\n\t";
3163 Result += utostr(NumMethods);
3164 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003165
Steve Naroff621edce2009-04-29 16:37:50 +00003166 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003167 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003168 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003169 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003170 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003171 Result += "\t ,{{(struct objc_selector *)\"";
3172 else
3173 Result += "\t ,{(struct objc_selector *)\"";
3174 Result += (*I)->getSelector().getAsString().c_str();
3175 std::string MethodTypeString;
3176 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3177 Result += "\", \"";
3178 Result += MethodTypeString;
3179 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003180 }
Steve Naroff621edce2009-04-29 16:37:50 +00003181 Result += "\t }\n};\n";
3182 }
3183
3184 // Output:
3185 /* struct _objc_protocol {
3186 // Objective-C 1.0 extensions
3187 struct _objc_protocol_extension *isa;
3188 char *protocol_name;
3189 struct _objc_protocol **protocol_list;
3190 struct _objc_protocol_method_list *instance_methods;
3191 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003192 };
Steve Naroff621edce2009-04-29 16:37:50 +00003193 */
3194 static bool objc_protocol = false;
3195 if (!objc_protocol) {
3196 Result += "\nstruct _objc_protocol {\n";
3197 Result += "\tstruct _objc_protocol_extension *isa;\n";
3198 Result += "\tchar *protocol_name;\n";
3199 Result += "\tstruct _objc_protocol **protocol_list;\n";
3200 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3201 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003202 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003203
Steve Naroff621edce2009-04-29 16:37:50 +00003204 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003205 }
Mike Stump1eb44332009-09-09 15:08:12 +00003206
Steve Naroff621edce2009-04-29 16:37:50 +00003207 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3208 Result += PDecl->getNameAsString();
3209 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3210 "{\n\t0, \"";
3211 Result += PDecl->getNameAsString();
3212 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003213 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003214 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3215 Result += PDecl->getNameAsString();
3216 Result += ", ";
3217 }
3218 else
3219 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003220 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003221 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3222 Result += PDecl->getNameAsString();
3223 Result += "\n";
3224 }
3225 else
3226 Result += "0\n";
3227 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003228
Steve Naroff621edce2009-04-29 16:37:50 +00003229 // Mark this protocol as having been generated.
3230 if (!ObjCSynthesizedProtocols.insert(PDecl))
3231 assert(false && "protocol already synthesized");
3232
3233}
3234
3235void RewriteObjC::
3236RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3237 const char *prefix, const char *ClassName,
3238 std::string &Result) {
3239 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003240
Steve Naroff621edce2009-04-29 16:37:50 +00003241 for (unsigned i = 0; i != Protocols.size(); i++)
3242 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3243
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003244 // Output the top lovel protocol meta-data for the class.
3245 /* struct _objc_protocol_list {
3246 struct _objc_protocol_list *next;
3247 int protocol_count;
3248 struct _objc_protocol *class_protocols[];
3249 }
3250 */
3251 Result += "\nstatic struct {\n";
3252 Result += "\tstruct _objc_protocol_list *next;\n";
3253 Result += "\tint protocol_count;\n";
3254 Result += "\tstruct _objc_protocol *class_protocols[";
3255 Result += utostr(Protocols.size());
3256 Result += "];\n} _OBJC_";
3257 Result += prefix;
3258 Result += "_PROTOCOLS_";
3259 Result += ClassName;
3260 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3261 "{\n\t0, ";
3262 Result += utostr(Protocols.size());
3263 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003264
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003265 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003266 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003267 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003268
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003269 for (unsigned i = 1; i != Protocols.size(); i++) {
3270 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003271 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003272 Result += "\n";
3273 }
3274 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003275}
3276
Steve Naroff621edce2009-04-29 16:37:50 +00003277
Mike Stump1eb44332009-09-09 15:08:12 +00003278/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003279/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003280void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003281 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003282 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003283 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003284 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003285 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003286 CDecl = CDecl->getNextClassCategory())
3287 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3288 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003289
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003290 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003291 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003292 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003293
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003294 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003295 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003296 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003297
3298 // If any of our property implementations have associated getters or
3299 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003300 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3301 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003302 Prop != PropEnd; ++Prop) {
3303 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3304 continue;
3305 if (!(*Prop)->getPropertyIvarDecl())
3306 continue;
3307 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3308 if (!PD)
3309 continue;
3310 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3311 InstanceMethods.push_back(Getter);
3312 if (PD->isReadOnly())
3313 continue;
3314 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3315 InstanceMethods.push_back(Setter);
3316 }
3317 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003318 true, "CATEGORY_", FullCategoryName.c_str(),
3319 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003320
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003321 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003322 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003323 false, "CATEGORY_", FullCategoryName.c_str(),
3324 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003325
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003326 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003327 // Null CDecl is case of a category implementation with no category interface
3328 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003329 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3330 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003331 /* struct _objc_category {
3332 char *category_name;
3333 char *class_name;
3334 struct _objc_method_list *instance_methods;
3335 struct _objc_method_list *class_methods;
3336 struct _objc_protocol_list *protocols;
3337 // Objective-C 1.0 extensions
3338 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003339 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003340 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003341 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003342 */
Mike Stump1eb44332009-09-09 15:08:12 +00003343
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003344 static bool objc_category = false;
3345 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003346 Result += "\nstruct _objc_category {\n";
3347 Result += "\tchar *category_name;\n";
3348 Result += "\tchar *class_name;\n";
3349 Result += "\tstruct _objc_method_list *instance_methods;\n";
3350 Result += "\tstruct _objc_method_list *class_methods;\n";
3351 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003352 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003353 Result += "\tstruct _objc_property_list *instance_properties;\n";
3354 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003355 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003356 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003357 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3358 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003359 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003360 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003361 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003362 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003363 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003364
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003365 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003366 Result += "\t, (struct _objc_method_list *)"
3367 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3368 Result += FullCategoryName;
3369 Result += "\n";
3370 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003371 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003372 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003373 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003374 Result += "\t, (struct _objc_method_list *)"
3375 "&_OBJC_CATEGORY_CLASS_METHODS_";
3376 Result += FullCategoryName;
3377 Result += "\n";
3378 }
3379 else
3380 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003381
Chris Lattnercafeb352009-02-20 18:18:36 +00003382 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003383 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003384 Result += FullCategoryName;
3385 Result += "\n";
3386 }
3387 else
3388 Result += "\t, 0\n";
3389 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003390}
3391
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003392/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3393/// ivar offset.
Mike Stump1eb44332009-09-09 15:08:12 +00003394void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3395 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003396 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003397 if (ivar->isBitField()) {
3398 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3399 // place all bitfields at offset 0.
3400 Result += "0";
3401 } else {
3402 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003403 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003404 if (LangOpts.Microsoft)
3405 Result += "_IMPL";
3406 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003407 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003408 Result += ")";
3409 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003410}
3411
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003412//===----------------------------------------------------------------------===//
3413// Meta Data Emission
3414//===----------------------------------------------------------------------===//
3415
Steve Naroffb29b4272008-04-14 22:03:09 +00003416void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003417 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003418 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003419
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003420 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003421 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003422 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003423 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003424 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003425 }
Mike Stump1eb44332009-09-09 15:08:12 +00003426
Chris Lattnerbe6df082007-12-12 07:56:42 +00003427 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003428 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003429 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003430 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003431 if (NumIvars > 0) {
3432 static bool objc_ivar = false;
3433 if (!objc_ivar) {
3434 /* struct _objc_ivar {
3435 char *ivar_name;
3436 char *ivar_type;
3437 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003438 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003439 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003440 Result += "\nstruct _objc_ivar {\n";
3441 Result += "\tchar *ivar_name;\n";
3442 Result += "\tchar *ivar_type;\n";
3443 Result += "\tint ivar_offset;\n";
3444 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003445
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003446 objc_ivar = true;
3447 }
3448
Steve Naroff946a6932008-03-11 00:12:29 +00003449 /* struct {
3450 int ivar_count;
3451 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003452 };
Steve Naroff946a6932008-03-11 00:12:29 +00003453 */
Mike Stump1eb44332009-09-09 15:08:12 +00003454 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003455 Result += "\tint ivar_count;\n";
3456 Result += "\tstruct _objc_ivar ivar_list[";
3457 Result += utostr(NumIvars);
3458 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003459 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003460 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003461 "{\n\t";
3462 Result += utostr(NumIvars);
3463 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003464
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003465 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003466 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003467 if (!IDecl->ivar_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003468 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003469 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003470 IV != IVEnd; ++IV)
3471 IVars.push_back(*IV);
3472 IVI = IVars.begin();
3473 IVE = IVars.end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003474 } else {
3475 IVI = CDecl->ivar_begin();
3476 IVE = CDecl->ivar_end();
3477 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003478 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003479 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003480 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003481 std::string TmpString, StrEncoding;
3482 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3483 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003484 Result += StrEncoding;
3485 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003486 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003487 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003488 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003489 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003490 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003491 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003492 std::string TmpString, StrEncoding;
3493 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3494 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003495 Result += StrEncoding;
3496 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003497 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003498 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003499 }
Mike Stump1eb44332009-09-09 15:08:12 +00003500
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003501 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003502 }
Mike Stump1eb44332009-09-09 15:08:12 +00003503
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003504 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003505 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003506 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003507
3508 // If any of our property implementations have associated getters or
3509 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003510 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3511 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003512 Prop != PropEnd; ++Prop) {
3513 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3514 continue;
3515 if (!(*Prop)->getPropertyIvarDecl())
3516 continue;
3517 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3518 if (!PD)
3519 continue;
3520 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3521 InstanceMethods.push_back(Getter);
3522 if (PD->isReadOnly())
3523 continue;
3524 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3525 InstanceMethods.push_back(Setter);
3526 }
3527 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003528 true, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003529
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003530 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003531 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003532 false, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003533
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003534 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003535 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3536 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003537
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003538 // Declaration of class/meta-class metadata
3539 /* struct _objc_class {
3540 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003541 const char *super_class_name;
3542 char *name;
3543 long version;
3544 long info;
3545 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003546 struct _objc_ivar_list *ivars;
3547 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003548 struct objc_cache *cache;
3549 struct objc_protocol_list *protocols;
3550 const char *ivar_layout;
3551 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003552 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003553 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003554 static bool objc_class = false;
3555 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003556 Result += "\nstruct _objc_class {\n";
3557 Result += "\tstruct _objc_class *isa;\n";
3558 Result += "\tconst char *super_class_name;\n";
3559 Result += "\tchar *name;\n";
3560 Result += "\tlong version;\n";
3561 Result += "\tlong info;\n";
3562 Result += "\tlong instance_size;\n";
3563 Result += "\tstruct _objc_ivar_list *ivars;\n";
3564 Result += "\tstruct _objc_method_list *methods;\n";
3565 Result += "\tstruct objc_cache *cache;\n";
3566 Result += "\tstruct _objc_protocol_list *protocols;\n";
3567 Result += "\tconst char *ivar_layout;\n";
3568 Result += "\tstruct _objc_class_ext *ext;\n";
3569 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003570 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003571 }
Mike Stump1eb44332009-09-09 15:08:12 +00003572
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003573 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003574 ObjCInterfaceDecl *RootClass = 0;
3575 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003576 while (SuperClass) {
3577 RootClass = SuperClass;
3578 SuperClass = SuperClass->getSuperClass();
3579 }
3580 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003581
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003582 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003583 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003584 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003585 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003586 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003587 Result += "\"";
3588
3589 if (SuperClass) {
3590 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003591 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003592 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003593 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003594 Result += "\"";
3595 }
3596 else {
3597 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003598 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003599 Result += "\"";
3600 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003601 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003602 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003603 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003604 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003605 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003606 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003607 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003608 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003609 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003610 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003611 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003612 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003613 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003614 Result += ",0,0\n";
3615 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003616 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003617 Result += "\t,0,0,0,0\n";
3618 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003619
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003620 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003621 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003622 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003623 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003624 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003625 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003626 if (SuperClass) {
3627 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003628 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003629 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003630 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003631 Result += "\"";
3632 }
3633 else {
3634 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003635 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003636 Result += "\"";
3637 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003638 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003639 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003640 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003641 Result += ",0";
3642 else {
3643 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003644 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003645 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003646 if (LangOpts.Microsoft)
3647 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003648 Result += ")";
3649 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003650 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003651 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003652 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003653 Result += "\n\t";
3654 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003655 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003656 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003657 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003658 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003659 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003660 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003661 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003662 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003663 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003664 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003665 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003666 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003667 Result += ", 0,0\n";
3668 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003669 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003670 Result += ",0,0,0\n";
3671 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003672}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003673
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003674/// RewriteImplementations - This routine rewrites all method implementations
3675/// and emits meta-data.
3676
Steve Narofface66252008-11-13 20:07:04 +00003677void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003678 int ClsDefCount = ClassImplementation.size();
3679 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003680
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003681 // Rewrite implemented methods
3682 for (int i = 0; i < ClsDefCount; i++)
3683 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003684
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003685 for (int i = 0; i < CatDefCount; i++)
3686 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003687}
Mike Stump1eb44332009-09-09 15:08:12 +00003688
Steve Narofface66252008-11-13 20:07:04 +00003689void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3690 int ClsDefCount = ClassImplementation.size();
3691 int CatDefCount = CategoryImplementation.size();
3692
Steve Naroff5df5b762008-05-07 21:23:49 +00003693 // This is needed for determining instance variable offsets.
Fariborz Jahanianc98cbb42010-01-07 18:31:42 +00003694 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003695 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003696 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003697 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003698
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003699 // For each implemented category, write out all its meta data.
3700 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003701 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00003702
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003703 // Write objc_symtab metadata
3704 /*
3705 struct _objc_symtab
3706 {
3707 long sel_ref_cnt;
3708 SEL *refs;
3709 short cls_def_cnt;
3710 short cat_def_cnt;
3711 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00003712 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003713 */
Mike Stump1eb44332009-09-09 15:08:12 +00003714
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003715 Result += "\nstruct _objc_symtab {\n";
3716 Result += "\tlong sel_ref_cnt;\n";
3717 Result += "\tSEL *refs;\n";
3718 Result += "\tshort cls_def_cnt;\n";
3719 Result += "\tshort cat_def_cnt;\n";
3720 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3721 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003722
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003723 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003724 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003725 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003726 + ", " + utostr(CatDefCount) + "\n";
3727 for (int i = 0; i < ClsDefCount; i++) {
3728 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003729 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003730 Result += "\n";
3731 }
Mike Stump1eb44332009-09-09 15:08:12 +00003732
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003733 for (int i = 0; i < CatDefCount; i++) {
3734 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003735 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003736 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003737 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003738 Result += "\n";
3739 }
Mike Stump1eb44332009-09-09 15:08:12 +00003740
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003741 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003742
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003743 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00003744
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003745 /*
3746 struct _objc_module {
3747 long version;
3748 long size;
3749 const char *name;
3750 struct _objc_symtab *symtab;
3751 }
3752 */
Mike Stump1eb44332009-09-09 15:08:12 +00003753
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003754 Result += "\nstruct _objc_module {\n";
3755 Result += "\tlong version;\n";
3756 Result += "\tlong size;\n";
3757 Result += "\tconst char *name;\n";
3758 Result += "\tstruct _objc_symtab *symtab;\n";
3759 Result += "};\n\n";
3760 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003761 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003762 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003763 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003764 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003765
3766 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00003767 if (ProtocolExprDecls.size()) {
3768 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3769 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003770 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00003771 E = ProtocolExprDecls.end(); I != E; ++I) {
3772 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3773 Result += (*I)->getNameAsString();
3774 Result += " = &_OBJC_PROTOCOL_";
3775 Result += (*I)->getNameAsString();
3776 Result += ";\n";
3777 }
3778 Result += "#pragma data_seg(pop)\n\n";
3779 }
Steve Naroff4f943c22008-03-10 20:43:59 +00003780 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003781 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003782 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3783 Result += "&_OBJC_MODULES;\n";
3784 Result += "#pragma data_seg(pop)\n\n";
3785 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003786}
Chris Lattner311ff022007-10-16 22:36:42 +00003787
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003788void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3789 const std::string &Name,
3790 ValueDecl *VD) {
3791 assert(BlockByRefDeclNo.count(VD) &&
3792 "RewriteByRefString: ByRef decl missing");
3793 ResultStr += "struct __Block_byref_" + Name +
3794 "_" + utostr(BlockByRefDeclNo[VD]) ;
3795}
3796
Steve Naroff54055232008-10-27 17:20:55 +00003797std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3798 const char *funcName,
3799 std::string Tag) {
3800 const FunctionType *AFT = CE->getFunctionType();
3801 QualType RT = AFT->getResultType();
3802 std::string StructRef = "struct " + Tag;
3803 std::string S = "static " + RT.getAsString() + " __" +
3804 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003805
Steve Naroff54055232008-10-27 17:20:55 +00003806 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003807
Douglas Gregor72564e72009-02-26 23:50:07 +00003808 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003809 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003810 // block (to reference imported block decl refs).
3811 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003812 } else if (BD->param_empty()) {
3813 S += "(" + StructRef + " *__cself)";
3814 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003815 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003816 assert(FT && "SynthesizeBlockFunc: No function proto");
3817 S += '(';
3818 // first add the implicit argument.
3819 S += StructRef + " *__cself, ";
3820 std::string ParamStr;
3821 for (BlockDecl::param_iterator AI = BD->param_begin(),
3822 E = BD->param_end(); AI != E; ++AI) {
3823 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003824 ParamStr = (*AI)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003825 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003826 S += ParamStr;
3827 }
3828 if (FT->isVariadic()) {
3829 if (!BD->param_empty()) S += ", ";
3830 S += "...";
3831 }
3832 S += ')';
3833 }
3834 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003835
Steve Naroff54055232008-10-27 17:20:55 +00003836 // Create local declarations to avoid rewriting all closure decl ref exprs.
3837 // First, emit a declaration for all "by ref" decls.
Mike Stump1eb44332009-09-09 15:08:12 +00003838 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003839 E = BlockByRefDecls.end(); I != E; ++I) {
3840 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003841 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003842 std::string TypeString;
3843 RewriteByRefString(TypeString, Name, (*I));
3844 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003845 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003846 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003847 }
Steve Naroff54055232008-10-27 17:20:55 +00003848 // Next, emit a declaration for all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003849 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003850 E = BlockByCopyDecls.end(); I != E; ++I) {
3851 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003852 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003853 // Handle nested closure invocation. For example:
3854 //
3855 // void (^myImportedClosure)(void);
3856 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003857 //
Steve Naroff54055232008-10-27 17:20:55 +00003858 // void (^anotherClosure)(void);
3859 // anotherClosure = ^(void) {
3860 // myImportedClosure(); // import and invoke the closure
3861 // };
3862 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003863 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003864 S += "struct __block_impl *";
3865 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003866 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003867 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003868 }
3869 std::string RewrittenStr = RewrittenBlockExprs[CE];
3870 const char *cstr = RewrittenStr.c_str();
3871 while (*cstr++ != '{') ;
3872 S += cstr;
3873 S += "\n";
3874 return S;
3875}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003876
Steve Naroff54055232008-10-27 17:20:55 +00003877std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3878 const char *funcName,
3879 std::string Tag) {
3880 std::string StructRef = "struct " + Tag;
3881 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00003882
Steve Naroff54055232008-10-27 17:20:55 +00003883 S += funcName;
3884 S += "_block_copy_" + utostr(i);
3885 S += "(" + StructRef;
3886 S += "*dst, " + StructRef;
3887 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003888 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003889 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003890 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003891 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003892 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003893 S += (*I)->getNameAsString();
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003894 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003895 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003896 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003897 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003898 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003899 S += "}\n";
3900
Steve Naroff54055232008-10-27 17:20:55 +00003901 S += "\nstatic void __";
3902 S += funcName;
3903 S += "_block_dispose_" + utostr(i);
3904 S += "(" + StructRef;
3905 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003906 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003907 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003908 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003909 S += (*I)->getNameAsString();
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003910 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003911 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003912 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003913 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003914 }
Mike Stump1eb44332009-09-09 15:08:12 +00003915 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00003916 return S;
3917}
3918
Steve Naroff01aec112009-12-06 21:14:13 +00003919std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3920 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00003921 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003922 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00003923
Steve Naroff54055232008-10-27 17:20:55 +00003924 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003925 S += " struct " + Desc;
3926 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003927
Steve Naroff01aec112009-12-06 21:14:13 +00003928 Constructor += "(void *fp, "; // Invoke function pointer.
3929 Constructor += "struct " + Desc; // Descriptor pointer.
3930 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00003931
Steve Naroff54055232008-10-27 17:20:55 +00003932 if (BlockDeclRefs.size()) {
3933 // Output all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003934 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003935 E = BlockByCopyDecls.end(); I != E; ++I) {
3936 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003937 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003938 std::string ArgName = "_" + FieldName;
3939 // Handle nested closure invocation. For example:
3940 //
3941 // void (^myImportedBlock)(void);
3942 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003943 //
Steve Naroff54055232008-10-27 17:20:55 +00003944 // void (^anotherBlock)(void);
3945 // anotherBlock = ^(void) {
3946 // myImportedBlock(); // import and invoke the closure
3947 // };
3948 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003949 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003950 S += "struct __block_impl *";
3951 Constructor += ", void *" + ArgName;
3952 } else {
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003953 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3954 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003955 Constructor += ", " + ArgName;
3956 }
3957 S += FieldName + ";\n";
3958 }
3959 // Output all "by ref" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003960 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003961 E = BlockByRefDecls.end(); I != E; ++I) {
3962 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003963 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003964 std::string ArgName = "_" + FieldName;
3965 // Handle nested closure invocation. For example:
3966 //
3967 // void (^myImportedBlock)(void);
3968 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003969 //
Steve Naroff54055232008-10-27 17:20:55 +00003970 // void (^anotherBlock)(void);
3971 // anotherBlock = ^(void) {
3972 // myImportedBlock(); // import and invoke the closure
3973 // };
3974 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003975 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003976 S += "struct __block_impl *";
3977 Constructor += ", void *" + ArgName;
3978 } else {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003979 std::string TypeString;
3980 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003981 TypeString += " *";
3982 FieldName = TypeString + FieldName;
3983 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00003984 Constructor += ", " + ArgName;
3985 }
3986 S += FieldName + "; // by ref\n";
3987 }
3988 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003989 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003990 if (GlobalVarDecl)
3991 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3992 else
3993 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003994 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003995
Steve Naroff01aec112009-12-06 21:14:13 +00003996 Constructor += " Desc = desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003997
Steve Naroff54055232008-10-27 17:20:55 +00003998 // Initialize all "by copy" arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003999 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004000 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004001 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004002 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004003 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00004004 Constructor += Name + " = (struct __block_impl *)_";
4005 else
4006 Constructor += Name + " = _";
4007 Constructor += Name + ";\n";
4008 }
4009 // Initialize all "by ref" arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004010 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004011 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004012 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004013 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004014 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00004015 Constructor += Name + " = (struct __block_impl *)_";
4016 else
4017 Constructor += Name + " = _";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004018 Constructor += Name + "->__forwarding;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004019 }
4020 } else {
4021 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004022 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004023 if (GlobalVarDecl)
4024 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4025 else
4026 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004027 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4028 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004029 }
4030 Constructor += " ";
4031 Constructor += "}\n";
4032 S += Constructor;
4033 S += "};\n";
4034 return S;
4035}
4036
Steve Naroff01aec112009-12-06 21:14:13 +00004037std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4038 std::string ImplTag, int i,
4039 const char *FunName,
4040 unsigned hasCopy) {
4041 std::string S = "\nstatic struct " + DescTag;
4042
4043 S += " {\n unsigned long reserved;\n";
4044 S += " unsigned long Block_size;\n";
4045 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004046 S += " void (*copy)(struct ";
4047 S += ImplTag; S += "*, struct ";
4048 S += ImplTag; S += "*);\n";
4049
4050 S += " void (*dispose)(struct ";
4051 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004052 }
4053 S += "} ";
4054
4055 S += DescTag + "_DATA = { 0, sizeof(struct ";
4056 S += ImplTag + ")";
4057 if (hasCopy) {
4058 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4059 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4060 }
4061 S += "};\n";
4062 return S;
4063}
4064
Steve Naroff54055232008-10-27 17:20:55 +00004065void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004066 const char *FunName) {
4067 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004068 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004069 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004070 // Insert closures that were part of the function.
4071 for (unsigned i = 0; i < Blocks.size(); i++) {
4072
4073 CollectBlockDeclRefInfo(Blocks[i]);
4074
Steve Naroff01aec112009-12-06 21:14:13 +00004075 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4076 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004077
Steve Naroff01aec112009-12-06 21:14:13 +00004078 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004079
4080 InsertText(FunLocStart, CI.c_str(), CI.size());
4081
Steve Naroff01aec112009-12-06 21:14:13 +00004082 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004083
Steve Naroff54055232008-10-27 17:20:55 +00004084 InsertText(FunLocStart, CF.c_str(), CF.size());
4085
4086 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004087 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Steve Naroff54055232008-10-27 17:20:55 +00004088 InsertText(FunLocStart, HF.c_str(), HF.size());
4089 }
Steve Naroff01aec112009-12-06 21:14:13 +00004090 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4091 ImportedBlockDecls.size() > 0);
4092 InsertText(FunLocStart, BD.c_str(), BD.size());
Mike Stump1eb44332009-09-09 15:08:12 +00004093
Steve Naroff54055232008-10-27 17:20:55 +00004094 BlockDeclRefs.clear();
4095 BlockByRefDecls.clear();
4096 BlockByCopyDecls.clear();
4097 BlockCallExprs.clear();
4098 ImportedBlockDecls.clear();
4099 }
4100 Blocks.clear();
4101 RewrittenBlockExprs.clear();
4102}
4103
4104void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4105 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00004106 const char *FuncName = FD->getNameAsCString();
Mike Stump1eb44332009-09-09 15:08:12 +00004107
Steve Naroff54055232008-10-27 17:20:55 +00004108 SynthesizeBlockLiterals(FunLocStart, FuncName);
4109}
4110
4111void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004112 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4113 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004114 SourceLocation FunLocStart = MD->getLocStart();
Chris Lattner077bf5e2008-11-24 03:33:13 +00004115 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004116 // Convert colons to underscores.
4117 std::string::size_type loc = 0;
4118 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4119 FuncName.replace(loc, 1, "_");
Mike Stump1eb44332009-09-09 15:08:12 +00004120
Steve Naroff54055232008-10-27 17:20:55 +00004121 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4122}
4123
4124void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4125 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4126 CI != E; ++CI)
4127 if (*CI) {
4128 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4129 GetBlockDeclRefExprs(CBE->getBody());
4130 else
4131 GetBlockDeclRefExprs(*CI);
4132 }
4133 // Handle specific things.
4134 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4135 // FIXME: Handle enums.
4136 if (!isa<FunctionDecl>(CDRE->getDecl()))
4137 BlockDeclRefs.push_back(CDRE);
4138 return;
4139}
4140
4141void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4142 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4143 CI != E; ++CI)
4144 if (*CI) {
4145 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4146 GetBlockCallExprs(CBE->getBody());
4147 else
4148 GetBlockCallExprs(*CI);
4149 }
Mike Stump1eb44332009-09-09 15:08:12 +00004150
Steve Naroff54055232008-10-27 17:20:55 +00004151 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4152 if (CE->getCallee()->getType()->isBlockPointerType()) {
4153 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4154 }
4155 }
4156 return;
4157}
4158
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004159Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004160 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004161 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004162
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004163 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004164 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004165 } else if (const BlockDeclRefExpr *CDRE =
4166 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004167 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004168 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004169 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004170 }
4171 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4172 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4173 }
4174 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4175 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4176 else if (const ConditionalOperator *CEXPR =
4177 dyn_cast<ConditionalOperator>(BlockExp)) {
4178 Expr *LHSExp = CEXPR->getLHS();
4179 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4180 Expr *RHSExp = CEXPR->getRHS();
4181 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4182 Expr *CONDExp = CEXPR->getCond();
4183 ConditionalOperator *CondExpr =
4184 new (Context) ConditionalOperator(CONDExp,
4185 SourceLocation(), cast<Expr>(LHSStmt),
4186 SourceLocation(), cast<Expr>(RHSStmt),
4187 Exp->getType());
4188 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004189 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4190 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004191 } else {
4192 assert(1 && "RewriteBlockClass: Bad type");
4193 }
4194 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004195 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004196 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004197 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004198 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004199
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004200 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4201 SourceLocation(),
4202 &Context->Idents.get("__block_impl"));
4203 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004204
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004205 // Generate a funky cast.
4206 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004207
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004208 // Push the block argument type.
4209 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004210 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004211 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004212 E = FTP->arg_type_end(); I && (I != E); ++I) {
4213 QualType t = *I;
4214 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004215 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004216 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004217 t = Context->getPointerType(BPT->getPointeeType());
4218 }
4219 ArgTypes.push_back(t);
4220 }
Steve Naroff54055232008-10-27 17:20:55 +00004221 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004222 // Now do the pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004223 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004224 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00004225
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004226 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004227
John McCall9d125032010-01-15 18:39:57 +00004228 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4229 CastExpr::CK_Unknown,
4230 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004231 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004232 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4233 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004234 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004235
Douglas Gregor44b43212008-12-11 16:49:14 +00004236 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004237 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004238 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004239 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4240 FD->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00004241
John McCall9d125032010-01-15 18:39:57 +00004242 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4243 CastExpr::CK_Unknown, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004244 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004245
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004246 llvm::SmallVector<Expr*, 8> BlkExprs;
4247 // Add the implicit argument.
4248 BlkExprs.push_back(BlkCast);
4249 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004250 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004251 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004252 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004253 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004254 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4255 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004256 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004257 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004258}
4259
4260void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004261 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004262 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00004263}
4264
Steve Naroff621edce2009-04-29 16:37:50 +00004265// We need to return the rewritten expression to handle cases where the
4266// BlockDeclRefExpr is embedded in another expression being rewritten.
4267// For example:
4268//
4269// int main() {
4270// __block Foo *f;
4271// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004272//
Steve Naroff621edce2009-04-29 16:37:50 +00004273// void (^myblock)() = ^() {
4274// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4275// i = 77;
4276// };
4277//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004278Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004279 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004280 // for each DeclRefExp where BYREFVAR is name of the variable.
4281 ValueDecl *VD;
4282 bool isArrow = true;
4283 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4284 VD = BDRE->getDecl();
4285 else {
4286 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4287 isArrow = false;
4288 }
4289
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004290 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4291 &Context->Idents.get("__forwarding"),
4292 Context->VoidPtrTy, 0,
4293 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004294 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4295 FD, SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004296 FD->getType());
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004297
4298 const char *Name = VD->getNameAsCString();
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004299 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4300 &Context->Idents.get(Name),
4301 Context->VoidPtrTy, 0,
4302 /*BitWidth=*/0, /*Mutable=*/true);
4303 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004304 DeclRefExp->getType());
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004305
4306
4307
Steve Naroffdf8570d2009-02-02 17:19:26 +00004308 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004309 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4310 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004311 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004312 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004313}
4314
Steve Naroffb2f9e512008-11-03 23:29:32 +00004315void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4316 SourceLocation LocStart = CE->getLParenLoc();
4317 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004318
4319 // Need to avoid trying to rewrite synthesized casts.
4320 if (LocStart.isInvalid())
4321 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004322 // Need to avoid trying to rewrite casts contained in macros.
4323 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4324 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004325
Steve Naroff54055232008-10-27 17:20:55 +00004326 const char *startBuf = SM->getCharacterData(LocStart);
4327 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004328 QualType QT = CE->getType();
4329 const Type* TypePtr = QT->getAs<Type>();
4330 if (isa<TypeOfExprType>(TypePtr)) {
4331 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4332 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4333 std::string TypeAsString = "(";
4334 TypeAsString += QT.getAsString();
4335 TypeAsString += ")";
4336 ReplaceText(LocStart, endBuf-startBuf+1,
4337 TypeAsString.c_str(), TypeAsString.size());
4338 return;
4339 }
Steve Naroff54055232008-10-27 17:20:55 +00004340 // advance the location to startArgList.
4341 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004342
Steve Naroff54055232008-10-27 17:20:55 +00004343 while (*argPtr++ && (argPtr < endBuf)) {
4344 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004345 case '^':
4346 // Replace the '^' with '*'.
4347 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4348 ReplaceText(LocStart, 1, "*", 1);
4349 break;
Steve Naroff54055232008-10-27 17:20:55 +00004350 }
4351 }
4352 return;
4353}
4354
4355void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4356 SourceLocation DeclLoc = FD->getLocation();
4357 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004358
Steve Naroff54055232008-10-27 17:20:55 +00004359 // We have 1 or more arguments that have closure pointers.
4360 const char *startBuf = SM->getCharacterData(DeclLoc);
4361 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004362
Steve Naroff54055232008-10-27 17:20:55 +00004363 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004364
Steve Naroff54055232008-10-27 17:20:55 +00004365 parenCount++;
4366 // advance the location to startArgList.
4367 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4368 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004369
Steve Naroff54055232008-10-27 17:20:55 +00004370 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004371
Steve Naroff54055232008-10-27 17:20:55 +00004372 while (*argPtr++ && parenCount) {
4373 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004374 case '^':
4375 // Replace the '^' with '*'.
4376 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4377 ReplaceText(DeclLoc, 1, "*", 1);
4378 break;
4379 case '(':
4380 parenCount++;
4381 break;
4382 case ')':
4383 parenCount--;
4384 break;
Steve Naroff54055232008-10-27 17:20:55 +00004385 }
4386 }
4387 return;
4388}
4389
4390bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004391 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004392 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004393 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004394 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004395 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004396 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004397 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004398 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004399 }
4400 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004401 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004402 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004403 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004404 return true;
4405 }
4406 return false;
4407}
4408
Ted Kremenek8189cde2009-02-07 01:47:29 +00004409void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4410 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004411 const char *argPtr = strchr(Name, '(');
4412 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004413
Steve Naroff54055232008-10-27 17:20:55 +00004414 LParen = argPtr; // output the start.
4415 argPtr++; // skip past the left paren.
4416 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004417
Steve Naroff54055232008-10-27 17:20:55 +00004418 while (*argPtr && parenCount) {
4419 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004420 case '(': parenCount++; break;
4421 case ')': parenCount--; break;
4422 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004423 }
4424 if (parenCount) argPtr++;
4425 }
4426 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4427 RParen = argPtr; // output the end
4428}
4429
4430void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4431 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4432 RewriteBlockPointerFunctionArgs(FD);
4433 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004434 }
Steve Naroff54055232008-10-27 17:20:55 +00004435 // Handle Variables and Typedefs.
4436 SourceLocation DeclLoc = ND->getLocation();
4437 QualType DeclT;
4438 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4439 DeclT = VD->getType();
4440 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4441 DeclT = TDD->getUnderlyingType();
4442 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4443 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004444 else
Steve Naroff54055232008-10-27 17:20:55 +00004445 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004446
Steve Naroff54055232008-10-27 17:20:55 +00004447 const char *startBuf = SM->getCharacterData(DeclLoc);
4448 const char *endBuf = startBuf;
4449 // scan backward (from the decl location) for the end of the previous decl.
4450 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4451 startBuf--;
Mike Stump1eb44332009-09-09 15:08:12 +00004452
Steve Naroff54055232008-10-27 17:20:55 +00004453 // *startBuf != '^' if we are dealing with a pointer to function that
4454 // may take block argument types (which will be handled below).
4455 if (*startBuf == '^') {
4456 // Replace the '^' with '*', computing a negative offset.
4457 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4458 ReplaceText(DeclLoc, 1, "*", 1);
4459 }
4460 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4461 // Replace the '^' with '*' for arguments.
4462 DeclLoc = ND->getLocation();
4463 startBuf = SM->getCharacterData(DeclLoc);
4464 const char *argListBegin, *argListEnd;
4465 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4466 while (argListBegin < argListEnd) {
4467 if (*argListBegin == '^') {
4468 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4469 ReplaceText(CaretLoc, 1, "*", 1);
4470 }
4471 argListBegin++;
4472 }
4473 }
4474 return;
4475}
4476
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004477
4478/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4479/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4480/// struct Block_byref_id_object *src) {
4481/// _Block_object_assign (&_dest->object, _src->object,
4482/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4483/// [|BLOCK_FIELD_IS_WEAK]) // object
4484/// _Block_object_assign(&_dest->object, _src->object,
4485/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4486/// [|BLOCK_FIELD_IS_WEAK]) // block
4487/// }
4488/// And:
4489/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4490/// _Block_object_dispose(_src->object,
4491/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4492/// [|BLOCK_FIELD_IS_WEAK]) // object
4493/// _Block_object_dispose(_src->object,
4494/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4495/// [|BLOCK_FIELD_IS_WEAK]) // block
4496/// }
4497
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004498std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4499 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004500 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004501 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004502 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004503 CopyDestroyCache.insert(flag);
4504 S = "static void __Block_byref_id_object_copy_";
4505 S += utostr(flag);
4506 S += "(void *dst, void *src) {\n";
4507
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004508 // offset into the object pointer is computed as:
4509 // void * + void* + int + int + void* + void *
4510 unsigned IntSize =
4511 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4512 unsigned VoidPtrSize =
4513 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4514
4515 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4516 S += " _Block_object_assign((char*)dst + ";
4517 S += utostr(offset);
4518 S += ", *(void * *) ((char*)src + ";
4519 S += utostr(offset);
4520 S += "), ";
4521 S += utostr(flag);
4522 S += ");\n}\n";
4523
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004524 S += "static void __Block_byref_id_object_dispose_";
4525 S += utostr(flag);
4526 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004527 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4528 S += utostr(offset);
4529 S += "), ";
4530 S += utostr(flag);
4531 S += ");\n}\n";
4532 return S;
4533}
4534
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004535/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4536/// the declaration into:
4537/// struct __Block_byref_ND {
4538/// void *__isa; // NULL for everything except __weak pointers
4539/// struct __Block_byref_ND *__forwarding;
4540/// int32_t __flags;
4541/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004542/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4543/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004544/// typex ND;
4545/// };
4546///
4547/// It then replaces declaration of ND variable with:
4548/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4549/// __size=sizeof(struct __Block_byref_ND),
4550/// ND=initializer-if-any};
4551///
4552///
4553void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004554 // Insert declaration for the function in which block literal is
4555 // used.
4556 if (CurFunctionDeclToDeclareForBlock)
4557 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004558 int flag = 0;
4559 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004560 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4561 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004562 SourceLocation X = ND->getLocEnd();
4563 X = SM->getInstantiationLoc(X);
4564 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004565 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004566 std::string ByrefType;
4567 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004568 ByrefType += " {\n";
4569 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004570 RewriteByRefString(ByrefType, Name, ND);
4571 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004572 ByrefType += " int __flags;\n";
4573 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004574 // Add void *__Block_byref_id_object_copy;
4575 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004576 QualType Ty = ND->getType();
4577 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4578 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004579 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4580 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004581 }
4582
4583 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004584 ByrefType += " " + Name + ";\n";
4585 ByrefType += "};\n";
4586 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004587 SourceLocation FunLocStart;
4588 if (CurFunctionDef)
4589 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4590 else {
4591 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4592 FunLocStart = CurMethodDef->getLocStart();
4593 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004594 InsertText(FunLocStart, ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004595 if (Ty.isObjCGCWeak()) {
4596 flag |= BLOCK_FIELD_IS_WEAK;
4597 isa = 1;
4598 }
4599
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004600 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004601 flag = BLOCK_BYREF_CALLER;
4602 QualType Ty = ND->getType();
4603 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4604 if (Ty->isBlockPointerType())
4605 flag |= BLOCK_FIELD_IS_BLOCK;
4606 else
4607 flag |= BLOCK_FIELD_IS_OBJECT;
4608 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004609 if (!HF.empty())
4610 InsertText(FunLocStart, HF.c_str(), HF.size());
4611 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004612
4613 // struct __Block_byref_ND ND =
4614 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4615 // initializer-if-any};
4616 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00004617 unsigned flags = 0;
4618 if (HasCopyAndDispose)
4619 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004620 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004621 ByrefType.clear();
4622 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004623 std::string ForwardingCastType("(");
4624 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004625 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004626 ByrefType += " " + Name + " = {(void*)";
4627 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004628 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004629 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004630 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004631 ByrefType += "sizeof(";
4632 RewriteByRefString(ByrefType, Name, ND);
4633 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004634 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004635 ByrefType += ", __Block_byref_id_object_copy_";
4636 ByrefType += utostr(flag);
4637 ByrefType += ", __Block_byref_id_object_dispose_";
4638 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004639 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004640 ByrefType += "};\n";
4641 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(),
4642 ByrefType.c_str(), ByrefType.size());
4643 }
4644 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004645 SourceLocation startLoc;
4646 Expr *E = ND->getInit();
4647 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4648 startLoc = ECE->getLParenLoc();
4649 else
4650 startLoc = E->getLocStart();
Fariborz Jahanian791b10d2010-01-05 23:06:29 +00004651 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004652 endBuf = SM->getCharacterData(startLoc);
4653
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004654 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004655 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004656 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004657 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004658 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004659 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004660 ByrefType += "sizeof(";
4661 RewriteByRefString(ByrefType, Name, ND);
4662 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004663 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004664 ByrefType += "__Block_byref_id_object_copy_";
4665 ByrefType += utostr(flag);
4666 ByrefType += ", __Block_byref_id_object_dispose_";
4667 ByrefType += utostr(flag);
4668 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004669 }
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004670 ReplaceText(DeclLoc, endBuf-startBuf,
4671 ByrefType.c_str(), ByrefType.size());
Steve Naroffc5143c52009-12-23 17:24:33 +00004672
4673 // Complete the newly synthesized compound expression by inserting a right
4674 // curly brace before the end of the declaration.
4675 // FIXME: This approach avoids rewriting the initializer expression. It
4676 // also assumes there is only one declarator. For example, the following
4677 // isn't currently supported by this routine (in general):
4678 //
4679 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4680 //
4681 const char *startBuf = SM->getCharacterData(startLoc);
4682 const char *semiBuf = strchr(startBuf, ';');
4683 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4684 SourceLocation semiLoc =
4685 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4686
4687 InsertText(semiLoc, "}", 1);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004688 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00004689 return;
4690}
4691
Mike Stump1eb44332009-09-09 15:08:12 +00004692void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004693 // Add initializers for any closure decl refs.
4694 GetBlockDeclRefExprs(Exp->getBody());
4695 if (BlockDeclRefs.size()) {
4696 // Unique all "by copy" declarations.
4697 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4698 if (!BlockDeclRefs[i]->isByRef())
4699 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4700 // Unique all "by ref" declarations.
4701 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4702 if (BlockDeclRefs[i]->isByRef()) {
4703 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4704 }
4705 // Find any imported blocks...they will need special attention.
4706 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004707 if (BlockDeclRefs[i]->isByRef() ||
4708 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4709 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff00072682008-11-13 17:40:07 +00004710 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00004711 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4712 }
4713 }
4714}
4715
Steve Narofffa15fd92008-10-28 20:29:00 +00004716FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4717 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004718 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00004719 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004720 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor2224f842009-02-25 16:33:18 +00004721 false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004722}
4723
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004724Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004725 Blocks.push_back(Exp);
4726
4727 CollectBlockDeclRefInfo(Exp);
4728 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004729
Steve Narofffa15fd92008-10-28 20:29:00 +00004730 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004731 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004732 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00004733 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004734 // Convert colons to underscores.
4735 std::string::size_type loc = 0;
4736 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4737 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004738 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004739 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004740
Steve Narofffa15fd92008-10-28 20:29:00 +00004741 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004742
Steve Narofffa15fd92008-10-28 20:29:00 +00004743 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4744 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00004745
Steve Narofffa15fd92008-10-28 20:29:00 +00004746 // Get a pointer to the function type so we can cast appropriately.
4747 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4748
4749 FunctionDecl *FD;
4750 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00004751
Steve Narofffa15fd92008-10-28 20:29:00 +00004752 // Simulate a contructor call...
4753 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004754 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004755
Steve Narofffa15fd92008-10-28 20:29:00 +00004756 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00004757
Steve Narofffdc03722008-10-29 21:23:59 +00004758 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00004759 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004760 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4761 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004762 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4763 CastExpr::CK_Unknown, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00004764 InitExprs.push_back(castExpr);
4765
Steve Naroff01aec112009-12-06 21:14:13 +00004766 // Initialize the block descriptor.
4767 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00004768
Steve Naroff01aec112009-12-06 21:14:13 +00004769 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4770 &Context->Idents.get(DescData.c_str()),
4771 Context->VoidPtrTy, 0,
4772 VarDecl::Static);
4773 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4774 new (Context) DeclRefExpr(NewVD,
4775 Context->VoidPtrTy, SourceLocation()),
4776 UnaryOperator::AddrOf,
4777 Context->getPointerType(Context->VoidPtrTy),
4778 SourceLocation());
4779 InitExprs.push_back(DescRefExpr);
4780
Steve Narofffa15fd92008-10-28 20:29:00 +00004781 // Add initializers for any closure decl refs.
4782 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004783 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004784 // Output all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00004785 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004786 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004787 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004788 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004789 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004790 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004791 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004792 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004793 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004794 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4795 CastExpr::CK_Unknown, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00004796 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004797 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004798 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004799 }
Mike Stump1eb44332009-09-09 15:08:12 +00004800 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004801 }
4802 // Output all "by ref" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00004803 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004804 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004805 ValueDecl *ND = (*I);
4806 std::string Name(ND->getNameAsString());
4807 std::string RecName;
4808 RewriteByRefString(RecName, Name, ND);
4809 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4810 + sizeof("struct"));
4811 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4812 SourceLocation(), II);
4813 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4814 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4815
Chris Lattner8ec03f52008-11-24 03:54:41 +00004816 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004817 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4818 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004819 Context->getPointerType(Exp->getType()),
Steve Narofffdc03722008-10-29 21:23:59 +00004820 SourceLocation());
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004821 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CastExpr::CK_Unknown, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00004822 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004823 }
4824 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00004825 if (ImportedBlockDecls.size()) {
4826 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4827 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00004828 unsigned IntSize =
4829 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianff127882009-12-23 21:52:32 +00004830 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
4831 Context->IntTy, SourceLocation());
4832 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00004833 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004834 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4835 FType, SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004836 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004837 Context->getPointerType(NewRep->getType()),
Steve Narofffa15fd92008-10-28 20:29:00 +00004838 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004839 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown,
4840 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00004841 BlockDeclRefs.clear();
4842 BlockByRefDecls.clear();
4843 BlockByCopyDecls.clear();
4844 ImportedBlockDecls.clear();
4845 return NewRep;
4846}
4847
4848//===----------------------------------------------------------------------===//
4849// Function Body / Expression rewriting
4850//===----------------------------------------------------------------------===//
4851
Steve Naroffc77a6362008-12-04 16:24:46 +00004852// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4853// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4854// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4855// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4856// Since the rewriter isn't capable of rewriting rewritten code, it's important
4857// we get this right.
4858void RewriteObjC::CollectPropertySetters(Stmt *S) {
4859 // Perform a bottom up traversal of all children.
4860 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4861 CI != E; ++CI)
4862 if (*CI)
4863 CollectPropertySetters(*CI);
4864
4865 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4866 if (BinOp->isAssignmentOp()) {
4867 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4868 PropSetters[PRE] = BinOp;
4869 }
4870 }
4871}
4872
Steve Narofffa15fd92008-10-28 20:29:00 +00004873Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00004874 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004875 isa<DoStmt>(S) || isa<ForStmt>(S))
4876 Stmts.push_back(S);
4877 else if (isa<ObjCForCollectionStmt>(S)) {
4878 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00004879 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00004880 }
Mike Stump1eb44332009-09-09 15:08:12 +00004881
Steve Narofffa15fd92008-10-28 20:29:00 +00004882 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004883
Steve Narofffa15fd92008-10-28 20:29:00 +00004884 // Perform a bottom up rewrite of all children.
4885 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4886 CI != E; ++CI)
4887 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00004888 Stmt *newStmt;
4889 Stmt *S = (*CI);
4890 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4891 Expr *OldBase = IvarRefExpr->getBase();
4892 bool replaced = false;
4893 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
4894 if (replaced) {
4895 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
4896 ReplaceStmt(OldBase, IRE->getBase());
4897 else
4898 ReplaceStmt(S, newStmt);
4899 }
4900 }
4901 else
4902 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump1eb44332009-09-09 15:08:12 +00004903 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00004904 *CI = newStmt;
4905 }
Mike Stump1eb44332009-09-09 15:08:12 +00004906
Steve Narofffa15fd92008-10-28 20:29:00 +00004907 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4908 // Rewrite the block body in place.
4909 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump1eb44332009-09-09 15:08:12 +00004910
Steve Narofffa15fd92008-10-28 20:29:00 +00004911 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenek6a12a142010-01-07 18:00:35 +00004912 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004913 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00004914
Steve Narofffa15fd92008-10-28 20:29:00 +00004915 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4916 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004917 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004918 return blockTranscribed;
4919 }
4920 // Handle specific things.
4921 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4922 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00004923
Steve Naroffc77a6362008-12-04 16:24:46 +00004924 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4925 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4926 if (BinOp) {
4927 // Because the rewriter doesn't allow us to rewrite rewritten code,
4928 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00004929 DisableReplaceStmt = true;
4930 // Save the source range. Even if we disable the replacement, the
4931 // rewritten node will have been inserted into the tree. If the synthesized
4932 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00004933 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00004934 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4935 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00004936 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00004937 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00004938 //
4939 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4940 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4941 // to see the original expression). Consider this example:
4942 //
4943 // Foo *obj1, *obj2;
4944 //
4945 // obj1.i = [obj2 rrrr];
4946 //
4947 // 'BinOp' for the previous expression looks like:
4948 //
4949 // (BinaryOperator 0x231ccf0 'int' '='
4950 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4951 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4952 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4953 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4954 //
4955 // 'newStmt' represents the rewritten message expression. For example:
4956 //
4957 // (CallExpr 0x231d300 'id':'struct objc_object *'
4958 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4959 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4960 // (CStyleCastExpr 0x231d220 'void *'
4961 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4962 //
4963 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4964 // can be used as the setter argument. ReplaceStmt() will still 'see'
4965 // the original RHS (since we haven't altered BinOp).
4966 //
Mike Stump1eb44332009-09-09 15:08:12 +00004967 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00004968 // node. As a result, we now leak the original AST nodes.
4969 //
Steve Naroffb619d952008-12-09 12:56:34 +00004970 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00004971 } else {
4972 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004973 }
4974 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004975 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4976 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00004977
Steve Narofffa15fd92008-10-28 20:29:00 +00004978 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4979 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00004980
Steve Narofffa15fd92008-10-28 20:29:00 +00004981 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004982#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004983 // Before we rewrite it, put the original message expression in a comment.
4984 SourceLocation startLoc = MessExpr->getLocStart();
4985 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00004986
Steve Narofffa15fd92008-10-28 20:29:00 +00004987 const char *startBuf = SM->getCharacterData(startLoc);
4988 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004989
Steve Narofffa15fd92008-10-28 20:29:00 +00004990 std::string messString;
4991 messString += "// ";
4992 messString.append(startBuf, endBuf-startBuf+1);
4993 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004994
4995 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00004996 // InsertText(clang::SourceLocation, char const*, unsigned int).
4997 // InsertText(startLoc, messString.c_str(), messString.size());
4998 // Tried this, but it didn't work either...
4999 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005000#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005001 return RewriteMessageExpr(MessExpr);
5002 }
Mike Stump1eb44332009-09-09 15:08:12 +00005003
Steve Narofffa15fd92008-10-28 20:29:00 +00005004 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5005 return RewriteObjCTryStmt(StmtTry);
5006
5007 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5008 return RewriteObjCSynchronizedStmt(StmtTry);
5009
5010 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5011 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005012
Steve Narofffa15fd92008-10-28 20:29:00 +00005013 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5014 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005015
5016 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005017 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005018 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005019 OrigStmtRange.getEnd());
5020 if (BreakStmt *StmtBreakStmt =
5021 dyn_cast<BreakStmt>(S))
5022 return RewriteBreakStmt(StmtBreakStmt);
5023 if (ContinueStmt *StmtContinueStmt =
5024 dyn_cast<ContinueStmt>(S))
5025 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005026
5027 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005028 // and cast exprs.
5029 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5030 // FIXME: What we're doing here is modifying the type-specifier that
5031 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005032 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005033 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5034 // the context of an ObjCForCollectionStmt. For example:
5035 // NSArray *someArray;
5036 // for (id <FooProtocol> index in someArray) ;
5037 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5038 // and it depends on the original text locations/positions.
Benjamin Kramerb2041de2009-12-05 22:16:51 +00005039 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005040 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005041
Steve Narofffa15fd92008-10-28 20:29:00 +00005042 // Blocks rewrite rules.
5043 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5044 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005045 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005046 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005047 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005048 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005049 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005050 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005051 if (VarDecl *VD = dyn_cast<VarDecl>(SD))
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005052 if (VD->hasAttr<BlocksAttr>()) {
5053 static unsigned uniqueByrefDeclCount = 0;
5054 assert(!BlockByRefDeclNo.count(ND) &&
5055 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5056 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005057 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005058 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005059 }
5060 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005061 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005062 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005063 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005064 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5065 }
5066 }
5067 }
Mike Stump1eb44332009-09-09 15:08:12 +00005068
Steve Narofffa15fd92008-10-28 20:29:00 +00005069 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5070 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005071
5072 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005073 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5074 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005075 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5076 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005077 && "Statement stack mismatch");
5078 Stmts.pop_back();
5079 }
5080 // Handle blocks rewriting.
5081 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5082 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005083 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005084 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005085 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5086 ValueDecl *VD = DRE->getDecl();
5087 if (VD->hasAttr<BlocksAttr>())
5088 return RewriteBlockDeclRefExpr(DRE);
5089 }
5090
Steve Narofffa15fd92008-10-28 20:29:00 +00005091 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005092 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005093 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005094 ReplaceStmt(S, BlockCall);
5095 return BlockCall;
5096 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005097 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005098 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005099 RewriteCastExpr(CE);
5100 }
5101#if 0
5102 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00005103 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005104 // Get the new text.
5105 std::string SStr;
5106 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005107 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005108 const std::string &Str = Buf.str();
5109
5110 printf("CAST = %s\n", &Str[0]);
5111 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5112 delete S;
5113 return Replacement;
5114 }
5115#endif
5116 // Return this stmt unmodified.
5117 return S;
5118}
5119
Steve Naroff3d7e7862009-12-05 15:55:59 +00005120void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5121 for (RecordDecl::field_iterator i = RD->field_begin(),
5122 e = RD->field_end(); i != e; ++i) {
5123 FieldDecl *FD = *i;
5124 if (isTopLevelBlockPointerType(FD->getType()))
5125 RewriteBlockPointerDecl(FD);
5126 if (FD->getType()->isObjCQualifiedIdType() ||
5127 FD->getType()->isObjCQualifiedInterfaceType())
5128 RewriteObjCQualifiedInterfaceTypes(FD);
5129 }
5130}
5131
Steve Narofffa15fd92008-10-28 20:29:00 +00005132/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5133/// main file of the input.
5134void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5135 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005136 if (FD->isOverloadedOperator())
5137 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005138
Steve Narofffa15fd92008-10-28 20:29:00 +00005139 // Since function prototypes don't have ParmDecl's, we check the function
5140 // prototype. This enables us to rewrite function declarations and
5141 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005142 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005143
Sebastian Redld3a413d2009-04-26 20:35:05 +00005144 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005145 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005146 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005147 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005148 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005149 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005150 Body =
5151 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5152 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005153 CurrentBody = 0;
5154 if (PropParentMap) {
5155 delete PropParentMap;
5156 PropParentMap = 0;
5157 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005158 // This synthesizes and inserts the block "impl" struct, invoke function,
5159 // and any copy/dispose helper functions.
5160 InsertBlockLiteralsWithinFunction(FD);
5161 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005162 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005163 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005164 return;
5165 }
5166 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005167 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005168 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005169 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005170 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005171 Body =
5172 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5173 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005174 CurrentBody = 0;
5175 if (PropParentMap) {
5176 delete PropParentMap;
5177 PropParentMap = 0;
5178 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005179 InsertBlockLiteralsWithinMethod(MD);
5180 CurMethodDef = 0;
5181 }
5182 }
5183 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5184 ClassImplementation.push_back(CI);
5185 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5186 CategoryImplementation.push_back(CI);
5187 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5188 RewriteForwardClassDecl(CD);
5189 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5190 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005191 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005192 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005193 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005194 CheckFunctionPointerDecl(VD->getType(), VD);
5195 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005196 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005197 RewriteCastExpr(CE);
5198 }
5199 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005200 } else if (VD->getType()->isRecordType()) {
5201 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5202 if (RD->isDefinition())
5203 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005204 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005205 if (VD->getInit()) {
5206 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005207 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005208 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005209 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005210 CurrentBody = 0;
5211 if (PropParentMap) {
5212 delete PropParentMap;
5213 PropParentMap = 0;
5214 }
Mike Stump1eb44332009-09-09 15:08:12 +00005215 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00005216 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005217 GlobalVarDecl = 0;
5218
5219 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005220 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005221 RewriteCastExpr(CE);
5222 }
5223 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005224 return;
5225 }
5226 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005227 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005228 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005229 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005230 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroff3d7e7862009-12-05 15:55:59 +00005231 else if (TD->getUnderlyingType()->isRecordType()) {
5232 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
5233 if (RD->isDefinition())
5234 RewriteRecordBody(RD);
5235 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005236 return;
5237 }
5238 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005239 if (RD->isDefinition())
5240 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005241 return;
5242 }
5243 // Nothing yet.
5244}
5245
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005246void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005247 // Get the top-level buffer that this corresponds to.
Mike Stump1eb44332009-09-09 15:08:12 +00005248
Steve Narofffa15fd92008-10-28 20:29:00 +00005249 // Rewrite tabs if we care.
5250 //RewriteTabs();
Mike Stump1eb44332009-09-09 15:08:12 +00005251
Steve Narofffa15fd92008-10-28 20:29:00 +00005252 if (Diags.hasErrorOccurred())
5253 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005254
Steve Narofffa15fd92008-10-28 20:29:00 +00005255 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005256
Steve Naroff621edce2009-04-29 16:37:50 +00005257 // Here's a great place to add any extra declarations that may be needed.
5258 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005259 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005260 E = ProtocolExprDecls.end(); I != E; ++I)
5261 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5262
Mike Stump1eb44332009-09-09 15:08:12 +00005263 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofffa15fd92008-10-28 20:29:00 +00005264 Preamble.c_str(), Preamble.size(), false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005265 if (ClassImplementation.size() || CategoryImplementation.size())
5266 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005267
Steve Narofffa15fd92008-10-28 20:29:00 +00005268 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5269 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005270 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005271 Rewrite.getRewriteBufferFor(MainFileID)) {
5272 //printf("Changed:\n");
5273 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5274 } else {
5275 fprintf(stderr, "No changes\n");
5276 }
Steve Narofface66252008-11-13 20:07:04 +00005277
Steve Naroff621edce2009-04-29 16:37:50 +00005278 if (ClassImplementation.size() || CategoryImplementation.size() ||
5279 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005280 // Rewrite Objective-c meta data*
5281 std::string ResultStr;
5282 SynthesizeMetaDataIntoBuffer(ResultStr);
5283 // Emit metadata.
5284 *OutFile << ResultStr;
5285 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005286 OutFile->flush();
5287}
5288