blob: 29f05788823e437342016e156c39b58e6c2212e6 [file] [log] [blame]
Steve Naroff1c9f81b2008-09-17 00:13:27 +00001//===--- RewriteBlocks.cpp ----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the closure rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman39d7c4d2009-05-18 22:50:54 +000014#include "clang/Frontend/ASTConsumers.h"
Steve Naroff1c9f81b2008-09-17 00:13:27 +000015#include "clang/Rewrite/Rewriter.h"
16#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/Basic/SourceManager.h"
19#include "clang/Basic/IdentifierTable.h"
20#include "clang/Basic/Diagnostic.h"
21#include "clang/Basic/LangOptions.h"
22#include "llvm/Support/MemoryBuffer.h"
23#include "llvm/ADT/StringExtras.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include <sstream>
26
27using namespace clang;
28using llvm::utostr;
29
30namespace {
31
32class RewriteBlocks : public ASTConsumer {
33 Rewriter Rewrite;
34 Diagnostic &Diags;
35 const LangOptions &LangOpts;
36 unsigned RewriteFailedDiag;
Steve Naroff1c9f81b2008-09-17 00:13:27 +000037
38 ASTContext *Context;
39 SourceManager *SM;
Chris Lattner2b2453a2009-01-17 06:22:33 +000040 FileID MainFileID;
Steve Naroff1c9f81b2008-09-17 00:13:27 +000041 const char *MainFileStart, *MainFileEnd;
42
43 // Block expressions.
44 llvm::SmallVector<BlockExpr *, 32> Blocks;
45 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
46 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
47
48 // Block related declarations.
49 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
50 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
Steve Naroff4e13b762008-10-03 20:28:15 +000051 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Steve Naroff70f95502008-10-04 17:06:23 +000052
53 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Steve Naroff1c9f81b2008-09-17 00:13:27 +000054
55 // The function/method we are rewriting.
56 FunctionDecl *CurFunctionDef;
57 ObjCMethodDecl *CurMethodDef;
58
59 bool IsHeader;
Steve Naroffa0b75cf2008-10-02 23:30:43 +000060
61 std::string Preamble;
Steve Naroff1c9f81b2008-09-17 00:13:27 +000062public:
Eli Friedman66d6f042009-05-18 22:20:00 +000063 RewriteBlocks(std::string inFile, Diagnostic &D,
Steve Naroff13188952008-09-18 14:10:13 +000064 const LangOptions &LOpts);
Steve Naroff1c9f81b2008-09-17 00:13:27 +000065 ~RewriteBlocks() {
66 // Get the buffer corresponding to MainFileID.
67 // If we haven't changed it, then we are done.
68 if (const RewriteBuffer *RewriteBuf =
69 Rewrite.getRewriteBufferFor(MainFileID)) {
70 std::string S(RewriteBuf->begin(), RewriteBuf->end());
71 printf("%s\n", S.c_str());
72 } else {
73 printf("No changes\n");
74 }
75 }
76
77 void Initialize(ASTContext &context);
78
79 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen);
80 void ReplaceText(SourceLocation Start, unsigned OrigLength,
81 const char *NewStr, unsigned NewLength);
82
83 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +000084 virtual void HandleTopLevelDecl(DeclGroupRef D) {
85 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
86 HandleTopLevelSingleDecl(*I);
87 }
88 void HandleTopLevelSingleDecl(Decl *D);
Steve Naroff1c9f81b2008-09-17 00:13:27 +000089 void HandleDeclInMainFile(Decl *D);
90
91 // Top level
92 Stmt *RewriteFunctionBody(Stmt *S);
93 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
94 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
95
96 // Block specific rewrite rules.
Steve Naroff70f95502008-10-04 17:06:23 +000097 std::string SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD=0);
Steve Naroff1c9f81b2008-09-17 00:13:27 +000098
99 void RewriteBlockCall(CallExpr *Exp);
100 void RewriteBlockPointerDecl(NamedDecl *VD);
Steve Naroff5e52b172008-10-04 18:52:47 +0000101 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000102 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
103
Steve Naroff4e13b762008-10-03 20:28:15 +0000104 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
105 const char *funcName, std::string Tag);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000106 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
107 const char *funcName, std::string Tag);
Steve Naroffacba0f22008-10-04 23:47:37 +0000108 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
109 bool hasCopyDisposeHelpers);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000110 std::string SynthesizeBlockCall(CallExpr *Exp);
111 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
112 const char *FunName);
113
Steve Naroffd3f77902008-10-05 00:06:12 +0000114 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000115 void GetBlockCallExprs(Stmt *S);
Steve Naroffacba0f22008-10-04 23:47:37 +0000116 void GetBlockDeclRefExprs(Stmt *S);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000117
118 // We avoid calling Type::isBlockPointerType(), since it operates on the
119 // canonical type. We only care if the top-level type is a closure pointer.
120 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
121
122 // FIXME: This predicate seems like it would be useful to add to ASTContext.
123 bool isObjCType(QualType T) {
124 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
125 return false;
126
127 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
128
129 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
130 OCT == Context->getCanonicalType(Context->getObjCClassType()))
131 return true;
132
133 if (const PointerType *PT = OCT->getAsPointerType()) {
134 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
135 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
136 return true;
137 }
138 return false;
139 }
140 // ObjC rewrite methods.
141 void RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl);
142 void RewriteCategoryDecl(ObjCCategoryDecl *CatDecl);
143 void RewriteProtocolDecl(ObjCProtocolDecl *PDecl);
144 void RewriteMethodDecl(ObjCMethodDecl *MDecl);
Steve Naroffca743602008-10-15 18:38:58 +0000145
Douglas Gregor72564e72009-02-26 23:50:07 +0000146 void RewriteFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroffca743602008-10-15 18:38:58 +0000147 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
148 void RewriteCastExpr(CastExpr *CE);
Steve Naroffeab5f632008-09-23 19:24:41 +0000149
Steve Naroffca743602008-10-15 18:38:58 +0000150 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000151 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000152};
153
154}
155
156static bool IsHeaderFile(const std::string &Filename) {
157 std::string::size_type DotPos = Filename.rfind('.');
158
159 if (DotPos == std::string::npos) {
160 // no file extension
161 return false;
162 }
163
164 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
165 // C header: .h
166 // C++ header: .hh or .H;
167 return Ext == "h" || Ext == "hh" || Ext == "H";
168}
169
Eli Friedman66d6f042009-05-18 22:20:00 +0000170RewriteBlocks::RewriteBlocks(std::string inFile,
Steve Naroff13188952008-09-18 14:10:13 +0000171 Diagnostic &D, const LangOptions &LOpts) :
172 Diags(D), LangOpts(LOpts) {
173 IsHeader = IsHeaderFile(inFile);
Steve Naroff13188952008-09-18 14:10:13 +0000174 CurFunctionDef = 0;
175 CurMethodDef = 0;
176 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
177 "rewriting failed");
Steve Naroff13188952008-09-18 14:10:13 +0000178}
179
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000180ASTConsumer *clang::CreateBlockRewriter(const std::string& InFile,
181 Diagnostic &Diags,
182 const LangOptions &LangOpts) {
Eli Friedman66d6f042009-05-18 22:20:00 +0000183 return new RewriteBlocks(InFile, Diags, LangOpts);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000184}
185
186void RewriteBlocks::Initialize(ASTContext &context) {
187 Context = &context;
188 SM = &Context->getSourceManager();
189
190 // Get the ID and start/end of the main file.
191 MainFileID = SM->getMainFileID();
192 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
193 MainFileStart = MainBuf->getBufferStart();
194 MainFileEnd = MainBuf->getBufferEnd();
195
Chris Lattner2c78b872009-04-14 23:22:57 +0000196 Rewrite.setSourceMgr(Context->getSourceManager(), LangOpts);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000197
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000198 if (IsHeader)
199 Preamble = "#pragma once\n";
200 Preamble += "#ifndef BLOCK_IMPL\n";
201 Preamble += "#define BLOCK_IMPL\n";
202 Preamble += "struct __block_impl {\n";
203 Preamble += " void *isa;\n";
204 Preamble += " int Flags;\n";
205 Preamble += " int Size;\n";
206 Preamble += " void *FuncPtr;\n";
207 Preamble += "};\n";
208 Preamble += "enum {\n";
209 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
210 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
211 Preamble += "};\n";
212 if (LangOpts.Microsoft)
213 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
214 else
215 Preamble += "#define __OBJC_RW_EXTERN extern\n";
216 Preamble += "// Runtime copy/destroy helper functions\n";
217 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
218 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
219 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
220 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
Steve Naroff48a8c612008-10-03 12:09:49 +0000221 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
222 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000223 Preamble += "#endif\n";
224
Chris Lattner2b2453a2009-01-17 06:22:33 +0000225 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000226 Preamble.c_str(), Preamble.size());
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000227}
228
229void RewriteBlocks::InsertText(SourceLocation Loc, const char *StrData,
230 unsigned StrLen)
231{
232 if (!Rewrite.InsertText(Loc, StrData, StrLen))
233 return;
234 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
235}
236
237void RewriteBlocks::ReplaceText(SourceLocation Start, unsigned OrigLength,
238 const char *NewStr, unsigned NewLength) {
239 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength))
240 return;
241 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
242}
243
244void RewriteBlocks::RewriteMethodDecl(ObjCMethodDecl *Method) {
245 bool haveBlockPtrs = false;
246 for (ObjCMethodDecl::param_iterator I = Method->param_begin(),
247 E = Method->param_end(); I != E; ++I)
248 if (isBlockPointerType((*I)->getType()))
249 haveBlockPtrs = true;
250
251 if (!haveBlockPtrs)
252 return;
253
254 // Do a fuzzy rewrite.
255 // We have 1 or more arguments that have closure pointers.
256 SourceLocation Loc = Method->getLocStart();
257 SourceLocation LocEnd = Method->getLocEnd();
258 const char *startBuf = SM->getCharacterData(Loc);
259 const char *endBuf = SM->getCharacterData(LocEnd);
260
261 const char *methodPtr = startBuf;
Steve Naroff8af6a452008-10-02 17:12:56 +0000262 std::string Tag = "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000263
264 while (*methodPtr++ && (methodPtr != endBuf)) {
265 switch (*methodPtr) {
266 case ':':
267 methodPtr++;
268 if (*methodPtr == '(') {
269 const char *scanType = ++methodPtr;
270 bool foundBlockPointer = false;
271 unsigned parenCount = 1;
272
273 while (parenCount) {
274 switch (*scanType) {
275 case '(':
276 parenCount++;
277 break;
278 case ')':
279 parenCount--;
280 break;
281 case '^':
282 foundBlockPointer = true;
283 break;
284 }
285 scanType++;
286 }
287 if (foundBlockPointer) {
288 // advance the location to startArgList.
289 Loc = Loc.getFileLocWithOffset(methodPtr-startBuf);
290 assert((Loc.isValid()) && "Invalid Loc");
291 ReplaceText(Loc, scanType-methodPtr-1, Tag.c_str(), Tag.size());
292
293 // Advance startBuf. Since the underlying buffer has changed,
294 // it's very important to advance startBuf (so we can correctly
295 // compute a relative Loc the next time around).
296 startBuf = methodPtr;
297 }
298 // Advance the method ptr to the end of the type.
299 methodPtr = scanType;
300 }
301 break;
302 }
303 }
304 return;
305}
306
307void RewriteBlocks::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Douglas Gregor6ab35242009-04-09 21:40:53 +0000308 for (ObjCInterfaceDecl::instmeth_iterator
309 I = ClassDecl->instmeth_begin(*Context),
310 E = ClassDecl->instmeth_end(*Context);
311 I != E; ++I)
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000312 RewriteMethodDecl(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000313 for (ObjCInterfaceDecl::classmeth_iterator
314 I = ClassDecl->classmeth_begin(*Context),
315 E = ClassDecl->classmeth_end(*Context);
316 I != E; ++I)
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000317 RewriteMethodDecl(*I);
318}
319
320void RewriteBlocks::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Douglas Gregor6ab35242009-04-09 21:40:53 +0000321 for (ObjCCategoryDecl::instmeth_iterator
322 I = CatDecl->instmeth_begin(*Context),
323 E = CatDecl->instmeth_end(*Context);
324 I != E; ++I)
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000325 RewriteMethodDecl(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000326 for (ObjCCategoryDecl::classmeth_iterator
327 I = CatDecl->classmeth_begin(*Context),
328 E = CatDecl->classmeth_end(*Context);
329 I != E; ++I)
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000330 RewriteMethodDecl(*I);
331}
332
333void RewriteBlocks::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Douglas Gregor6ab35242009-04-09 21:40:53 +0000334 for (ObjCProtocolDecl::instmeth_iterator
335 I = PDecl->instmeth_begin(*Context),
336 E = PDecl->instmeth_end(*Context);
337 I != E; ++I)
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000338 RewriteMethodDecl(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000339 for (ObjCProtocolDecl::classmeth_iterator
340 I = PDecl->classmeth_begin(*Context),
341 E = PDecl->classmeth_end(*Context);
342 I != E; ++I)
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000343 RewriteMethodDecl(*I);
344}
345
346//===----------------------------------------------------------------------===//
347// Top Level Driver Code
348//===----------------------------------------------------------------------===//
349
Chris Lattner682bf922009-03-29 16:50:03 +0000350void RewriteBlocks::HandleTopLevelSingleDecl(Decl *D) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000351 // Two cases: either the decl could be in the main file, or it could be in a
352 // #included file. If the former, rewrite it now. If the later, check to see
353 // if we rewrote the #include/#import.
354 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000355 Loc = SM->getInstantiationLoc(Loc);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000356
357 // If this is for a builtin, ignore it.
358 if (Loc.isInvalid()) return;
359
360 if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D))
361 RewriteInterfaceDecl(MD);
362 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D))
363 RewriteCategoryDecl(CD);
364 else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
365 RewriteProtocolDecl(PD);
366
367 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner23f2c582009-01-25 22:02:19 +0000368 if (SM->isFromMainFile(Loc))
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000369 HandleDeclInMainFile(D);
370 return;
371}
372
373std::string RewriteBlocks::SynthesizeBlockFunc(BlockExpr *CE, int i,
374 const char *funcName,
375 std::string Tag) {
376 const FunctionType *AFT = CE->getFunctionType();
377 QualType RT = AFT->getResultType();
Steve Naroff48a8c612008-10-03 12:09:49 +0000378 std::string StructRef = "struct " + Tag;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000379 std::string S = "static " + RT.getAsString() + " __" +
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000380 funcName + "_" + "block_func_" + utostr(i);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000381
Steve Naroff56ee6892008-10-08 17:01:13 +0000382 BlockDecl *BD = CE->getBlockDecl();
383
Douglas Gregor72564e72009-02-26 23:50:07 +0000384 if (isa<FunctionNoProtoType>(AFT)) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000385 S += "()";
Steve Naroff56ee6892008-10-08 17:01:13 +0000386 } else if (BD->param_empty()) {
Steve Naroff48a8c612008-10-03 12:09:49 +0000387 S += "(" + StructRef + " *__cself)";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000388 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +0000389 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000390 assert(FT && "SynthesizeBlockFunc: No function proto");
391 S += '(';
392 // first add the implicit argument.
Steve Naroff48a8c612008-10-03 12:09:49 +0000393 S += StructRef + " *__cself, ";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000394 std::string ParamStr;
Steve Naroff56ee6892008-10-08 17:01:13 +0000395 for (BlockDecl::param_iterator AI = BD->param_begin(),
396 E = BD->param_end(); AI != E; ++AI) {
397 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000398 ParamStr = (*AI)->getNameAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000399 (*AI)->getType().getAsStringInternal(ParamStr);
400 S += ParamStr;
401 }
402 if (FT->isVariadic()) {
Steve Naroff56ee6892008-10-08 17:01:13 +0000403 if (!BD->param_empty()) S += ", ";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000404 S += "...";
405 }
406 S += ')';
407 }
408 S += " {\n";
409
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000410 // Create local declarations to avoid rewriting all closure decl ref exprs.
411 // First, emit a declaration for all "by ref" decls.
412 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
413 E = BlockByRefDecls.end(); I != E; ++I) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000414 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000415 std::string Name = (*I)->getNameAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000416 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000417 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000418 }
419 // Next, emit a declaration for all "by copy" declarations.
420 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
421 E = BlockByCopyDecls.end(); I != E; ++I) {
422 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000423 std::string Name = (*I)->getNameAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000424 // Handle nested closure invocation. For example:
425 //
426 // void (^myImportedClosure)(void);
427 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
428 //
429 // void (^anotherClosure)(void);
430 // anotherClosure = ^(void) {
431 // myImportedClosure(); // import and invoke the closure
432 // };
433 //
434 if (isBlockPointerType((*I)->getType()))
Steve Naroff8af6a452008-10-02 17:12:56 +0000435 S += "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000436 else
437 (*I)->getType().getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000438 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000439 }
Steve Naroff70f95502008-10-04 17:06:23 +0000440 std::string RewrittenStr = RewrittenBlockExprs[CE];
441 const char *cstr = RewrittenStr.c_str();
442 while (*cstr++ != '{') ;
443 S += cstr;
444 S += "\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000445 return S;
446}
447
Steve Naroff4e13b762008-10-03 20:28:15 +0000448std::string RewriteBlocks::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
449 const char *funcName,
450 std::string Tag) {
451 std::string StructRef = "struct " + Tag;
452 std::string S = "static void __";
453
454 S += funcName;
455 S += "_block_copy_" + utostr(i);
456 S += "(" + StructRef;
457 S += "*dst, " + StructRef;
458 S += "*src) {";
459 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
460 E = ImportedBlockDecls.end(); I != E; ++I) {
461 S += "_Block_copy_assign(&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000462 S += (*I)->getNameAsString();
Steve Naroff4e13b762008-10-03 20:28:15 +0000463 S += ", src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000464 S += (*I)->getNameAsString();
Steve Naroff4e13b762008-10-03 20:28:15 +0000465 S += ");}";
466 }
467 S += "\nstatic void __";
468 S += funcName;
469 S += "_block_dispose_" + utostr(i);
470 S += "(" + StructRef;
471 S += "*src) {";
472 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
473 E = ImportedBlockDecls.end(); I != E; ++I) {
474 S += "_Block_destroy(src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000475 S += (*I)->getNameAsString();
Steve Naroff4e13b762008-10-03 20:28:15 +0000476 S += ");";
477 }
478 S += "}\n";
479 return S;
480}
481
Steve Naroffacba0f22008-10-04 23:47:37 +0000482std::string RewriteBlocks::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
483 bool hasCopyDisposeHelpers) {
Steve Naroff48a8c612008-10-03 12:09:49 +0000484 std::string S = "struct " + Tag;
485 std::string Constructor = " " + Tag;
486
487 S += " {\n struct __block_impl impl;\n";
Steve Naroffacba0f22008-10-04 23:47:37 +0000488
489 if (hasCopyDisposeHelpers)
490 S += " void *copy;\n void *dispose;\n";
491
Steve Naroff48a8c612008-10-03 12:09:49 +0000492 Constructor += "(void *fp";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000493
Steve Naroffacba0f22008-10-04 23:47:37 +0000494 if (hasCopyDisposeHelpers)
495 Constructor += ", void *copyHelp, void *disposeHelp";
496
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000497 if (BlockDeclRefs.size()) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000498 // Output all "by copy" declarations.
499 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
500 E = BlockByCopyDecls.end(); I != E; ++I) {
501 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000502 std::string FieldName = (*I)->getNameAsString();
Steve Naroff4e13b762008-10-03 20:28:15 +0000503 std::string ArgName = "_" + FieldName;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000504 // Handle nested closure invocation. For example:
505 //
506 // void (^myImportedBlock)(void);
507 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
508 //
509 // void (^anotherBlock)(void);
510 // anotherBlock = ^(void) {
511 // myImportedBlock(); // import and invoke the closure
512 // };
513 //
Steve Naroff4e13b762008-10-03 20:28:15 +0000514 if (isBlockPointerType((*I)->getType())) {
Steve Naroff8af6a452008-10-02 17:12:56 +0000515 S += "struct __block_impl *";
Steve Naroff4e13b762008-10-03 20:28:15 +0000516 Constructor += ", void *" + ArgName;
517 } else {
518 (*I)->getType().getAsStringInternal(FieldName);
Steve Naroff48a8c612008-10-03 12:09:49 +0000519 (*I)->getType().getAsStringInternal(ArgName);
Steve Naroff4e13b762008-10-03 20:28:15 +0000520 Constructor += ", " + ArgName;
Steve Naroff48a8c612008-10-03 12:09:49 +0000521 }
Steve Naroff4e13b762008-10-03 20:28:15 +0000522 S += FieldName + ";\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000523 }
524 // Output all "by ref" declarations.
525 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
526 E = BlockByRefDecls.end(); I != E; ++I) {
527 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000528 std::string FieldName = (*I)->getNameAsString();
Steve Naroff4e13b762008-10-03 20:28:15 +0000529 std::string ArgName = "_" + FieldName;
530 // Handle nested closure invocation. For example:
531 //
532 // void (^myImportedBlock)(void);
533 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
534 //
535 // void (^anotherBlock)(void);
536 // anotherBlock = ^(void) {
537 // myImportedBlock(); // import and invoke the closure
538 // };
539 //
540 if (isBlockPointerType((*I)->getType())) {
Steve Naroff8af6a452008-10-02 17:12:56 +0000541 S += "struct __block_impl *";
Steve Naroff4e13b762008-10-03 20:28:15 +0000542 Constructor += ", void *" + ArgName;
543 } else {
544 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
Steve Naroff48a8c612008-10-03 12:09:49 +0000545 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
Steve Naroff4e13b762008-10-03 20:28:15 +0000546 Constructor += ", " + ArgName;
Steve Naroff48a8c612008-10-03 12:09:49 +0000547 }
Steve Naroff4e13b762008-10-03 20:28:15 +0000548 S += FieldName + "; // by ref\n";
Steve Naroff48a8c612008-10-03 12:09:49 +0000549 }
550 // Finish writing the constructor.
551 // FIXME: handle NSConcreteGlobalBlock.
552 Constructor += ", int flags=0) {\n";
Steve Naroff83ba14e2008-10-03 15:04:50 +0000553 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
Steve Naroff48a8c612008-10-03 12:09:49 +0000554 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
555
Steve Naroffacba0f22008-10-04 23:47:37 +0000556 if (hasCopyDisposeHelpers)
557 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
558
Steve Naroff48a8c612008-10-03 12:09:49 +0000559 // Initialize all "by copy" arguments.
560 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
561 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000562 std::string Name = (*I)->getNameAsString();
Steve Naroff48a8c612008-10-03 12:09:49 +0000563 Constructor += " ";
Steve Naroff4e13b762008-10-03 20:28:15 +0000564 if (isBlockPointerType((*I)->getType()))
565 Constructor += Name + " = (struct __block_impl *)_";
566 else
567 Constructor += Name + " = _";
Steve Naroff48a8c612008-10-03 12:09:49 +0000568 Constructor += Name + ";\n";
569 }
570 // Initialize all "by ref" arguments.
571 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
572 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000573 std::string Name = (*I)->getNameAsString();
Steve Naroff48a8c612008-10-03 12:09:49 +0000574 Constructor += " ";
Steve Naroff4e13b762008-10-03 20:28:15 +0000575 if (isBlockPointerType((*I)->getType()))
576 Constructor += Name + " = (struct __block_impl *)_";
577 else
578 Constructor += Name + " = _";
Steve Naroff48a8c612008-10-03 12:09:49 +0000579 Constructor += Name + ";\n";
580 }
Steve Naroff83ba14e2008-10-03 15:04:50 +0000581 } else {
582 // Finish writing the constructor.
583 // FIXME: handle NSConcreteGlobalBlock.
584 Constructor += ", int flags=0) {\n";
585 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
586 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Steve Naroffacba0f22008-10-04 23:47:37 +0000587 if (hasCopyDisposeHelpers)
588 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000589 }
Steve Naroff83ba14e2008-10-03 15:04:50 +0000590 Constructor += " ";
591 Constructor += "}\n";
592 S += Constructor;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000593 S += "};\n";
594 return S;
595}
596
597void RewriteBlocks::SynthesizeBlockLiterals(SourceLocation FunLocStart,
598 const char *FunName) {
599 // Insert closures that were part of the function.
600 for (unsigned i = 0; i < Blocks.size(); i++) {
Steve Naroffacba0f22008-10-04 23:47:37 +0000601
Steve Naroffd3f77902008-10-05 00:06:12 +0000602 CollectBlockDeclRefInfo(Blocks[i]);
603
Steve Naroff48a8c612008-10-03 12:09:49 +0000604 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000605
Steve Naroffacba0f22008-10-04 23:47:37 +0000606 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
607 ImportedBlockDecls.size() > 0);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000608
609 InsertText(FunLocStart, CI.c_str(), CI.size());
Steve Naroff4e13b762008-10-03 20:28:15 +0000610
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000611 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
612
613 InsertText(FunLocStart, CF.c_str(), CF.size());
614
Steve Naroff4e13b762008-10-03 20:28:15 +0000615 if (ImportedBlockDecls.size()) {
616 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
617 InsertText(FunLocStart, HF.c_str(), HF.size());
618 }
619
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000620 BlockDeclRefs.clear();
621 BlockByRefDecls.clear();
622 BlockByCopyDecls.clear();
623 BlockCallExprs.clear();
Steve Naroff4e13b762008-10-03 20:28:15 +0000624 ImportedBlockDecls.clear();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000625 }
626 Blocks.clear();
Steve Naroff8e9216d2008-10-04 17:10:02 +0000627 RewrittenBlockExprs.clear();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000628}
629
630void RewriteBlocks::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Steve Naroff3ad29e22008-10-03 00:12:09 +0000631 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +0000632 const char *FuncName = FD->getNameAsCString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000633
634 SynthesizeBlockLiterals(FunLocStart, FuncName);
635}
636
637void RewriteBlocks::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
638 SourceLocation FunLocStart = MD->getLocStart();
Chris Lattner077bf5e2008-11-24 03:33:13 +0000639 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000640 // Convert colons to underscores.
641 std::string::size_type loc = 0;
642 while ((loc = FuncName.find(":", loc)) != std::string::npos)
643 FuncName.replace(loc, 1, "_");
644
645 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
646}
647
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000648void RewriteBlocks::GetBlockDeclRefExprs(Stmt *S) {
649 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
650 CI != E; ++CI)
Steve Naroff84a969f2008-10-08 17:31:13 +0000651 if (*CI) {
652 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
653 GetBlockDeclRefExprs(CBE->getBody());
654 else
655 GetBlockDeclRefExprs(*CI);
656 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000657 // Handle specific things.
658 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
659 // FIXME: Handle enums.
660 if (!isa<FunctionDecl>(CDRE->getDecl()))
661 BlockDeclRefs.push_back(CDRE);
662 return;
663}
664
665void RewriteBlocks::GetBlockCallExprs(Stmt *S) {
666 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
667 CI != E; ++CI)
Steve Naroff84a969f2008-10-08 17:31:13 +0000668 if (*CI) {
669 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
670 GetBlockCallExprs(CBE->getBody());
671 else
672 GetBlockCallExprs(*CI);
673 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000674
675 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff4e13b762008-10-03 20:28:15 +0000676 if (CE->getCallee()->getType()->isBlockPointerType()) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000677 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
Steve Naroff4e13b762008-10-03 20:28:15 +0000678 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000679 }
680 return;
681}
682
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000683std::string RewriteBlocks::SynthesizeBlockCall(CallExpr *Exp) {
684 // Navigate to relevant type information.
Steve Naroffcc2ece22008-09-24 22:46:45 +0000685 const char *closureName = 0;
686 const BlockPointerType *CPT = 0;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000687
688 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +0000689 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000690 CPT = DRE->getType()->getAsBlockPointerType();
691 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +0000692 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000693 CPT = CDRE->getType()->getAsBlockPointerType();
Steve Naroff83ba14e2008-10-03 15:04:50 +0000694 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +0000695 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff83ba14e2008-10-03 15:04:50 +0000696 CPT = MExpr->getType()->getAsBlockPointerType();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000697 } else {
698 assert(1 && "RewriteBlockClass: Bad type");
699 }
700 assert(CPT && "RewriteBlockClass: Bad type");
701 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
702 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +0000703 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000704 // FTP will be null for closures that don't take arguments.
705
706 // Build a closure call - start with a paren expr to enforce precedence.
707 std::string BlockCall = "(";
708
709 // Synthesize the cast.
710 BlockCall += "(" + Exp->getType().getAsString() + "(*)";
Steve Naroff8af6a452008-10-02 17:12:56 +0000711 BlockCall += "(struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000712 if (FTP) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000713 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000714 E = FTP->arg_type_end(); I && (I != E); ++I)
715 BlockCall += ", " + (*I).getAsString();
716 }
717 BlockCall += "))"; // close the argument list and paren expression.
718
Steve Naroff83ba14e2008-10-03 15:04:50 +0000719 // Invoke the closure. We need to cast it since the declaration type is
720 // bogus (it's a function pointer type)
721 BlockCall += "((struct __block_impl *)";
722 std::string closureExprBufStr;
723 llvm::raw_string_ostream closureExprBuf(closureExprBufStr);
724 Exp->getCallee()->printPretty(closureExprBuf);
725 BlockCall += closureExprBuf.str();
726 BlockCall += ")->FuncPtr)";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000727
728 // Add the arguments.
Steve Naroff83ba14e2008-10-03 15:04:50 +0000729 BlockCall += "((struct __block_impl *)";
Steve Naroffb65a4f12008-10-04 17:45:51 +0000730 BlockCall += closureExprBuf.str();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000731 for (CallExpr::arg_iterator I = Exp->arg_begin(),
732 E = Exp->arg_end(); I != E; ++I) {
733 std::string syncExprBufS;
734 llvm::raw_string_ostream Buf(syncExprBufS);
735 (*I)->printPretty(Buf);
736 BlockCall += ", " + Buf.str();
737 }
738 return BlockCall;
739}
740
741void RewriteBlocks::RewriteBlockCall(CallExpr *Exp) {
742 std::string BlockCall = SynthesizeBlockCall(Exp);
743
744 const char *startBuf = SM->getCharacterData(Exp->getLocStart());
745 const char *endBuf = SM->getCharacterData(Exp->getLocEnd());
746
747 ReplaceText(Exp->getLocStart(), endBuf-startBuf,
748 BlockCall.c_str(), BlockCall.size());
749}
750
Steve Naroff5e52b172008-10-04 18:52:47 +0000751void RewriteBlocks::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
752 // FIXME: Add more elaborate code generation required by the ABI.
753 InsertText(BDRE->getLocStart(), "*", 1);
754}
755
Steve Naroffca743602008-10-15 18:38:58 +0000756void RewriteBlocks::RewriteCastExpr(CastExpr *CE) {
757 SourceLocation LocStart = CE->getLocStart();
758 SourceLocation LocEnd = CE->getLocEnd();
759
Steve Naroff8f6ce572008-11-03 11:20:24 +0000760 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
761 return;
762
Steve Naroffca743602008-10-15 18:38:58 +0000763 const char *startBuf = SM->getCharacterData(LocStart);
764 const char *endBuf = SM->getCharacterData(LocEnd);
765
766 // advance the location to startArgList.
767 const char *argPtr = startBuf;
768
769 while (*argPtr++ && (argPtr < endBuf)) {
770 switch (*argPtr) {
771 case '^':
772 // Replace the '^' with '*'.
773 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
774 ReplaceText(LocStart, 1, "*", 1);
775 break;
776 }
777 }
778 return;
779}
780
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000781void RewriteBlocks::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
782 SourceLocation DeclLoc = FD->getLocation();
Steve Naroffe0109a52008-10-10 15:33:34 +0000783 unsigned parenCount = 0;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000784
785 // We have 1 or more arguments that have closure pointers.
786 const char *startBuf = SM->getCharacterData(DeclLoc);
787 const char *startArgList = strchr(startBuf, '(');
788
789 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
790
791 parenCount++;
792 // advance the location to startArgList.
Steve Naroffe0109a52008-10-10 15:33:34 +0000793 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000794 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
795
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000796 const char *argPtr = startArgList;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000797
798 while (*argPtr++ && parenCount) {
799 switch (*argPtr) {
800 case '^':
Steve Naroffe0109a52008-10-10 15:33:34 +0000801 // Replace the '^' with '*'.
802 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
803 ReplaceText(DeclLoc, 1, "*", 1);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000804 break;
805 case '(':
806 parenCount++;
807 break;
808 case ')':
809 parenCount--;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000810 break;
811 }
812 }
813 return;
814}
815
Steve Naroffca743602008-10-15 18:38:58 +0000816bool RewriteBlocks::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000817 const FunctionProtoType *FTP;
Steve Naroffca743602008-10-15 18:38:58 +0000818 const PointerType *PT = QT->getAsPointerType();
819 if (PT) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000820 FTP = PT->getPointeeType()->getAsFunctionProtoType();
Steve Naroffca743602008-10-15 18:38:58 +0000821 } else {
822 const BlockPointerType *BPT = QT->getAsBlockPointerType();
823 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
Douglas Gregor72564e72009-02-26 23:50:07 +0000824 FTP = BPT->getPointeeType()->getAsFunctionProtoType();
Steve Naroffca743602008-10-15 18:38:58 +0000825 }
Steve Naroffeab5f632008-09-23 19:24:41 +0000826 if (FTP) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000827 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffeab5f632008-09-23 19:24:41 +0000828 E = FTP->arg_type_end(); I != E; ++I)
829 if (isBlockPointerType(*I))
830 return true;
831 }
832 return false;
833}
834
835void RewriteBlocks::GetExtentOfArgList(const char *Name,
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000836 const char *&LParen, const char *&RParen) {
837 const char *argPtr = strchr(Name, '(');
Steve Naroffeab5f632008-09-23 19:24:41 +0000838 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
839
840 LParen = argPtr; // output the start.
841 argPtr++; // skip past the left paren.
842 unsigned parenCount = 1;
843
844 while (*argPtr && parenCount) {
845 switch (*argPtr) {
846 case '(': parenCount++; break;
847 case ')': parenCount--; break;
848 default: break;
849 }
850 if (parenCount) argPtr++;
851 }
852 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
853 RParen = argPtr; // output the end
854}
855
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000856void RewriteBlocks::RewriteBlockPointerDecl(NamedDecl *ND) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000857 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
858 RewriteBlockPointerFunctionArgs(FD);
859 return;
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000860 }
861 // Handle Variables and Typedefs.
862 SourceLocation DeclLoc = ND->getLocation();
863 QualType DeclT;
864 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
865 DeclT = VD->getType();
866 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
867 DeclT = TDD->getUnderlyingType();
Steve Naroff83ba14e2008-10-03 15:04:50 +0000868 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
869 DeclT = FD->getType();
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000870 else
871 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Steve Naroffeab5f632008-09-23 19:24:41 +0000872
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000873 const char *startBuf = SM->getCharacterData(DeclLoc);
874 const char *endBuf = startBuf;
875 // scan backward (from the decl location) for the end of the previous decl.
876 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
877 startBuf--;
Steve Naroffca743602008-10-15 18:38:58 +0000878
879 // *startBuf != '^' if we are dealing with a pointer to function that
880 // may take block argument types (which will be handled below).
881 if (*startBuf == '^') {
882 // Replace the '^' with '*', computing a negative offset.
883 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
884 ReplaceText(DeclLoc, 1, "*", 1);
885 }
886 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000887 // Replace the '^' with '*' for arguments.
888 DeclLoc = ND->getLocation();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000889 startBuf = SM->getCharacterData(DeclLoc);
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000890 const char *argListBegin, *argListEnd;
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000891 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
892 while (argListBegin < argListEnd) {
893 if (*argListBegin == '^') {
894 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
895 ReplaceText(CaretLoc, 1, "*", 1);
896 }
897 argListBegin++;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000898 }
Steve Naroffeab5f632008-09-23 19:24:41 +0000899 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000900 return;
901}
902
Steve Naroffd3f77902008-10-05 00:06:12 +0000903void RewriteBlocks::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000904 // Add initializers for any closure decl refs.
Steve Naroff84a969f2008-10-08 17:31:13 +0000905 GetBlockDeclRefExprs(Exp->getBody());
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000906 if (BlockDeclRefs.size()) {
907 // Unique all "by copy" declarations.
908 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
909 if (!BlockDeclRefs[i]->isByRef())
910 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
911 // Unique all "by ref" declarations.
912 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
913 if (BlockDeclRefs[i]->isByRef()) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000914 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
915 }
Steve Naroffacba0f22008-10-04 23:47:37 +0000916 // Find any imported blocks...they will need special attention.
917 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
918 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
919 GetBlockCallExprs(Blocks[i]);
920 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
921 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000922 }
Steve Naroffd3f77902008-10-05 00:06:12 +0000923}
924
925std::string RewriteBlocks::SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD) {
926 Blocks.push_back(Exp);
927
928 CollectBlockDeclRefInfo(Exp);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000929 std::string FuncName;
930
931 if (CurFunctionDef)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000932 FuncName = std::string(CurFunctionDef->getNameAsString());
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000933 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +0000934 FuncName = CurMethodDef->getSelector().getAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000935 // Convert colons to underscores.
936 std::string::size_type loc = 0;
937 while ((loc = FuncName.find(":", loc)) != std::string::npos)
938 FuncName.replace(loc, 1, "_");
Steve Naroff39622b92008-10-03 15:38:09 +0000939 } else if (VD)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000940 FuncName = std::string(VD->getNameAsString());
Steve Naroff39622b92008-10-03 15:38:09 +0000941
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000942 std::string BlockNumber = utostr(Blocks.size()-1);
943
Steve Naroff83ba14e2008-10-03 15:04:50 +0000944 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000945 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000946
Steve Naroff83ba14e2008-10-03 15:04:50 +0000947 std::string FunkTypeStr;
948
949 // Get a pointer to the function type so we can cast appropriately.
950 Context->getPointerType(QualType(Exp->getFunctionType(),0)).getAsStringInternal(FunkTypeStr);
951
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000952 // Rewrite the closure block with a compound literal. The first cast is
953 // to prevent warnings from the C compiler.
Steve Naroff83ba14e2008-10-03 15:04:50 +0000954 std::string Init = "(" + FunkTypeStr;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000955
Steve Naroff83ba14e2008-10-03 15:04:50 +0000956 Init += ")&" + Tag;
957
958 // Initialize the block function.
959 Init += "((void*)" + Func;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000960
Steve Naroffacba0f22008-10-04 23:47:37 +0000961 if (ImportedBlockDecls.size()) {
962 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
963 Init += ",(void*)" + Buf;
964 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
965 Init += ",(void*)" + Buf;
966 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000967 // Add initializers for any closure decl refs.
968 if (BlockDeclRefs.size()) {
969 // Output all "by copy" declarations.
970 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
971 E = BlockByCopyDecls.end(); I != E; ++I) {
972 Init += ",";
973 if (isObjCType((*I)->getType())) {
974 Init += "[[";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000975 Init += (*I)->getNameAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000976 Init += " retain] autorelease]";
Steve Naroff4e13b762008-10-03 20:28:15 +0000977 } else if (isBlockPointerType((*I)->getType())) {
978 Init += "(void *)";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000979 Init += (*I)->getNameAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000980 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000981 Init += (*I)->getNameAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000982 }
983 }
984 // Output all "by ref" declarations.
985 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
986 E = BlockByRefDecls.end(); I != E; ++I) {
987 Init += ",&";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000988 Init += (*I)->getNameAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000989 }
990 }
Steve Naroff83ba14e2008-10-03 15:04:50 +0000991 Init += ")";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000992 BlockDeclRefs.clear();
993 BlockByRefDecls.clear();
994 BlockByCopyDecls.clear();
Steve Naroff4e13b762008-10-03 20:28:15 +0000995 ImportedBlockDecls.clear();
996
Steve Naroff70f95502008-10-04 17:06:23 +0000997 return Init;
998}
999
1000//===----------------------------------------------------------------------===//
1001// Function Body / Expression rewriting
1002//===----------------------------------------------------------------------===//
1003
1004Stmt *RewriteBlocks::RewriteFunctionBody(Stmt *S) {
1005 // Start by rewriting all children.
1006 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1007 CI != E; ++CI)
1008 if (*CI) {
1009 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
Steve Naroff84a969f2008-10-08 17:31:13 +00001010 Stmt *newStmt = RewriteFunctionBody(CBE->getBody());
Steve Naroff70f95502008-10-04 17:06:23 +00001011 if (newStmt)
1012 *CI = newStmt;
1013
1014 // We've just rewritten the block body in place.
1015 // Now we snarf the rewritten text and stash it away for later use.
1016 std::string S = Rewrite.getRewritenText(CBE->getSourceRange());
1017 RewrittenBlockExprs[CBE] = S;
1018 std::string Init = SynthesizeBlockInitExpr(CBE);
1019 // Do the rewrite, using S.size() which contains the rewritten size.
1020 ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size());
1021 } else {
1022 Stmt *newStmt = RewriteFunctionBody(*CI);
1023 if (newStmt)
1024 *CI = newStmt;
1025 }
1026 }
1027 // Handle specific things.
1028 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1029 if (CE->getCallee()->getType()->isBlockPointerType())
1030 RewriteBlockCall(CE);
1031 }
Steve Naroffca743602008-10-15 18:38:58 +00001032 if (CastExpr *CE = dyn_cast<CastExpr>(S)) {
1033 RewriteCastExpr(CE);
1034 }
Steve Naroff70f95502008-10-04 17:06:23 +00001035 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
Ted Kremenekfda4fed2008-10-06 18:47:09 +00001036 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
1037 DI != DE; ++DI) {
1038
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001039 Decl *SD = *DI;
Ted Kremenekfda4fed2008-10-06 18:47:09 +00001040 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
1041 if (isBlockPointerType(ND->getType()))
1042 RewriteBlockPointerDecl(ND);
Steve Naroffca743602008-10-15 18:38:58 +00001043 else if (ND->getType()->isFunctionPointerType())
1044 CheckFunctionPointerDecl(ND->getType(), ND);
Ted Kremenekfda4fed2008-10-06 18:47:09 +00001045 }
1046 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
1047 if (isBlockPointerType(TD->getUnderlyingType()))
1048 RewriteBlockPointerDecl(TD);
Steve Naroffca743602008-10-15 18:38:58 +00001049 else if (TD->getUnderlyingType()->isFunctionPointerType())
1050 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Ted Kremenekfda4fed2008-10-06 18:47:09 +00001051 }
Steve Naroff70f95502008-10-04 17:06:23 +00001052 }
1053 }
Steve Naroff5e52b172008-10-04 18:52:47 +00001054 // Handle specific things.
1055 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
1056 if (BDRE->isByRef())
1057 RewriteBlockDeclRefExpr(BDRE);
1058 }
Steve Naroff70f95502008-10-04 17:06:23 +00001059 // Return this stmt unmodified.
1060 return S;
1061}
1062
Douglas Gregor72564e72009-02-26 23:50:07 +00001063void RewriteBlocks::RewriteFunctionProtoType(QualType funcType, NamedDecl *D) {
1064 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
1065 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroffca743602008-10-15 18:38:58 +00001066 E = fproto->arg_type_end(); I && (I != E); ++I)
1067 if (isBlockPointerType(*I)) {
1068 // All the args are checked/rewritten. Don't call twice!
1069 RewriteBlockPointerDecl(D);
1070 break;
1071 }
1072 }
1073}
1074
1075void RewriteBlocks::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
1076 const PointerType *PT = funcType->getAsPointerType();
1077 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +00001078 RewriteFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroffca743602008-10-15 18:38:58 +00001079}
1080
Steve Naroff70f95502008-10-04 17:06:23 +00001081/// HandleDeclInMainFile - This is called for each top-level decl defined in the
1082/// main file of the input.
1083void RewriteBlocks::HandleDeclInMainFile(Decl *D) {
1084 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff70f95502008-10-04 17:06:23 +00001085 // Since function prototypes don't have ParmDecl's, we check the function
1086 // prototype. This enables us to rewrite function declarations and
1087 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00001088 RewriteFunctionProtoType(FD->getType(), FD);
Sebastian Redld3a413d2009-04-26 20:35:05 +00001089
1090 // FIXME: Handle CXXTryStmt
1091 if (CompoundStmt *Body = FD->getCompoundBody(*Context)) {
Steve Naroff70f95502008-10-04 17:06:23 +00001092 CurFunctionDef = FD;
Ted Kremenekeaab2062009-03-12 18:33:24 +00001093 FD->setBody(cast_or_null<CompoundStmt>(RewriteFunctionBody(Body)));
Steve Naroff70f95502008-10-04 17:06:23 +00001094 // This synthesizes and inserts the block "impl" struct, invoke function,
1095 // and any copy/dispose helper functions.
1096 InsertBlockLiteralsWithinFunction(FD);
1097 CurFunctionDef = 0;
1098 }
1099 return;
1100 }
1101 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
1102 RewriteMethodDecl(MD);
Douglas Gregor72971342009-04-18 00:02:19 +00001103 if (Stmt *Body = MD->getBody(*Context)) {
Steve Naroff70f95502008-10-04 17:06:23 +00001104 CurMethodDef = MD;
1105 RewriteFunctionBody(Body);
1106 InsertBlockLiteralsWithinMethod(MD);
1107 CurMethodDef = 0;
1108 }
1109 }
1110 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1111 if (isBlockPointerType(VD->getType())) {
1112 RewriteBlockPointerDecl(VD);
1113 if (VD->getInit()) {
1114 if (BlockExpr *CBE = dyn_cast<BlockExpr>(VD->getInit())) {
Douglas Gregor72971342009-04-18 00:02:19 +00001115 RewriteFunctionBody(CBE->getBody(*Context));
Steve Naroff70f95502008-10-04 17:06:23 +00001116
1117 // We've just rewritten the block body in place.
1118 // Now we snarf the rewritten text and stash it away for later use.
1119 std::string S = Rewrite.getRewritenText(CBE->getSourceRange());
1120 RewrittenBlockExprs[CBE] = S;
1121 std::string Init = SynthesizeBlockInitExpr(CBE, VD);
1122 // Do the rewrite, using S.size() which contains the rewritten size.
1123 ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size());
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001124 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00001125 VD->getNameAsCString());
Steve Naroffca743602008-10-15 18:38:58 +00001126 } else if (CastExpr *CE = dyn_cast<CastExpr>(VD->getInit())) {
1127 RewriteCastExpr(CE);
1128 }
1129 }
1130 } else if (VD->getType()->isFunctionPointerType()) {
1131 CheckFunctionPointerDecl(VD->getType(), VD);
1132 if (VD->getInit()) {
1133 if (CastExpr *CE = dyn_cast<CastExpr>(VD->getInit())) {
1134 RewriteCastExpr(CE);
Steve Naroff70f95502008-10-04 17:06:23 +00001135 }
1136 }
1137 }
1138 return;
1139 }
1140 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
1141 if (isBlockPointerType(TD->getUnderlyingType()))
1142 RewriteBlockPointerDecl(TD);
Steve Naroffca743602008-10-15 18:38:58 +00001143 else if (TD->getUnderlyingType()->isFunctionPointerType())
1144 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroff70f95502008-10-04 17:06:23 +00001145 return;
1146 }
1147 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1148 if (RD->isDefinition()) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00001149 for (RecordDecl::field_iterator i = RD->field_begin(*Context),
1150 e = RD->field_end(*Context); i != e; ++i) {
Steve Naroff70f95502008-10-04 17:06:23 +00001151 FieldDecl *FD = *i;
1152 if (isBlockPointerType(FD->getType()))
1153 RewriteBlockPointerDecl(FD);
1154 }
1155 }
1156 return;
1157 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +00001158}