blob: 190c745d3d00715cacf24c9d0a680198d6eaff0b [file] [log] [blame]
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
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 code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Rewrite/ASTConsumers.h"
15#include "clang/Rewrite/Rewriter.h"
16#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ParentMap.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Lex/Lexer.h"
23#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/DenseSet.h"
29
30using namespace clang;
31using llvm::utostr;
32
33namespace {
34 class RewriteModernObjC : public ASTConsumer {
35 protected:
36
37 enum {
38 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
39 block, ... */
40 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
41 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
42 __block variable */
43 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
44 helpers */
45 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
46 support routines */
47 BLOCK_BYREF_CURRENT_MAX = 256
48 };
49
50 enum {
51 BLOCK_NEEDS_FREE = (1 << 24),
52 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
53 BLOCK_HAS_CXX_OBJ = (1 << 26),
54 BLOCK_IS_GC = (1 << 27),
55 BLOCK_IS_GLOBAL = (1 << 28),
56 BLOCK_HAS_DESCRIPTOR = (1 << 29)
57 };
58 static const int OBJC_ABI_VERSION = 7;
59
60 Rewriter Rewrite;
61 DiagnosticsEngine &Diags;
62 const LangOptions &LangOpts;
63 ASTContext *Context;
64 SourceManager *SM;
65 TranslationUnitDecl *TUDecl;
66 FileID MainFileID;
67 const char *MainFileStart, *MainFileEnd;
68 Stmt *CurrentBody;
69 ParentMap *PropParentMap; // created lazily.
70 std::string InFileName;
71 raw_ostream* OutFile;
72 std::string Preamble;
73
74 TypeDecl *ProtocolTypeDecl;
75 VarDecl *GlobalVarDecl;
76 unsigned RewriteFailedDiag;
77 // ObjC string constant support.
78 unsigned NumObjCStringLiterals;
79 VarDecl *ConstantStringClassReference;
80 RecordDecl *NSStringRecord;
81
82 // ObjC foreach break/continue generation support.
83 int BcLabelCount;
84
85 unsigned TryFinallyContainsReturnDiag;
86 // Needed for super.
87 ObjCMethodDecl *CurMethodDef;
88 RecordDecl *SuperStructDecl;
89 RecordDecl *ConstantStringDecl;
90
91 FunctionDecl *MsgSendFunctionDecl;
92 FunctionDecl *MsgSendSuperFunctionDecl;
93 FunctionDecl *MsgSendStretFunctionDecl;
94 FunctionDecl *MsgSendSuperStretFunctionDecl;
95 FunctionDecl *MsgSendFpretFunctionDecl;
96 FunctionDecl *GetClassFunctionDecl;
97 FunctionDecl *GetMetaClassFunctionDecl;
98 FunctionDecl *GetSuperClassFunctionDecl;
99 FunctionDecl *SelGetUidFunctionDecl;
100 FunctionDecl *CFStringFunctionDecl;
101 FunctionDecl *SuperContructorFunctionDecl;
102 FunctionDecl *CurFunctionDef;
103 FunctionDecl *CurFunctionDeclToDeclareForBlock;
104
105 /* Misc. containers needed for meta-data rewrite. */
106 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
107 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
108 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
109 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
111 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
112 SmallVector<Stmt *, 32> Stmts;
113 SmallVector<int, 8> ObjCBcLabelNo;
114 // Remember all the @protocol(<expr>) expressions.
115 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
116
117 llvm::DenseSet<uint64_t> CopyDestroyCache;
118
119 // Block expressions.
120 SmallVector<BlockExpr *, 32> Blocks;
121 SmallVector<int, 32> InnerDeclRefsCount;
122 SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
123
124 SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
125
126 // Block related declarations.
127 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
129 SmallVector<ValueDecl *, 8> BlockByRefDecls;
130 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
131 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
132 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
133 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
134
135 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
136
137 // This maps an original source AST to it's rewritten form. This allows
138 // us to avoid rewriting the same node twice (which is very uncommon).
139 // This is needed to support some of the exotic property rewriting.
140 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
141
142 // Needed for header files being rewritten
143 bool IsHeader;
144 bool SilenceRewriteMacroWarning;
145 bool objc_impl_method;
146
147 bool DisableReplaceStmt;
148 class DisableReplaceStmtScope {
149 RewriteModernObjC &R;
150 bool SavedValue;
151
152 public:
153 DisableReplaceStmtScope(RewriteModernObjC &R)
154 : R(R), SavedValue(R.DisableReplaceStmt) {
155 R.DisableReplaceStmt = true;
156 }
157 ~DisableReplaceStmtScope() {
158 R.DisableReplaceStmt = SavedValue;
159 }
160 };
161 void InitializeCommon(ASTContext &context);
162
163 public:
164
165 // Top Level Driver code.
166 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
167 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
168 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
169 if (!Class->isThisDeclarationADefinition()) {
170 RewriteForwardClassDecl(D);
171 break;
172 }
173 }
174
175 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
176 if (!Proto->isThisDeclarationADefinition()) {
177 RewriteForwardProtocolDecl(D);
178 break;
179 }
180 }
181
182 HandleTopLevelSingleDecl(*I);
183 }
184 return true;
185 }
186 void HandleTopLevelSingleDecl(Decl *D);
187 void HandleDeclInMainFile(Decl *D);
188 RewriteModernObjC(std::string inFile, raw_ostream *OS,
189 DiagnosticsEngine &D, const LangOptions &LOpts,
190 bool silenceMacroWarn);
191
192 ~RewriteModernObjC() {}
193
194 virtual void HandleTranslationUnit(ASTContext &C);
195
196 void ReplaceStmt(Stmt *Old, Stmt *New) {
197 Stmt *ReplacingStmt = ReplacedNodes[Old];
198
199 if (ReplacingStmt)
200 return; // We can't rewrite the same node twice.
201
202 if (DisableReplaceStmt)
203 return;
204
205 // If replacement succeeded or warning disabled return with no warning.
206 if (!Rewrite.ReplaceStmt(Old, New)) {
207 ReplacedNodes[Old] = New;
208 return;
209 }
210 if (SilenceRewriteMacroWarning)
211 return;
212 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
213 << Old->getSourceRange();
214 }
215
216 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
217 if (DisableReplaceStmt)
218 return;
219
220 // Measure the old text.
221 int Size = Rewrite.getRangeSize(SrcRange);
222 if (Size == -1) {
223 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
224 << Old->getSourceRange();
225 return;
226 }
227 // Get the new text.
228 std::string SStr;
229 llvm::raw_string_ostream S(SStr);
230 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
231 const std::string &Str = S.str();
232
233 // If replacement succeeded or warning disabled return with no warning.
234 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
235 ReplacedNodes[Old] = New;
236 return;
237 }
238 if (SilenceRewriteMacroWarning)
239 return;
240 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
241 << Old->getSourceRange();
242 }
243
244 void InsertText(SourceLocation Loc, StringRef Str,
245 bool InsertAfter = true) {
246 // If insertion succeeded or warning disabled return with no warning.
247 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
248 SilenceRewriteMacroWarning)
249 return;
250
251 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
252 }
253
254 void ReplaceText(SourceLocation Start, unsigned OrigLength,
255 StringRef Str) {
256 // If removal succeeded or warning disabled return with no warning.
257 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
258 SilenceRewriteMacroWarning)
259 return;
260
261 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
262 }
263
264 // Syntactic Rewriting.
265 void RewriteRecordBody(RecordDecl *RD);
266 void RewriteInclude();
267 void RewriteForwardClassDecl(DeclGroupRef D);
268 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
269 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
270 const std::string &typedefString);
271 void RewriteImplementations();
272 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
273 ObjCImplementationDecl *IMD,
274 ObjCCategoryImplDecl *CID);
275 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
276 void RewriteImplementationDecl(Decl *Dcl);
277 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
278 ObjCMethodDecl *MDecl, std::string &ResultStr);
279 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
280 const FunctionType *&FPRetType);
281 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
282 ValueDecl *VD, bool def=false);
283 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
284 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
285 void RewriteForwardProtocolDecl(DeclGroupRef D);
286 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
287 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
288 void RewriteProperty(ObjCPropertyDecl *prop);
289 void RewriteFunctionDecl(FunctionDecl *FD);
290 void RewriteBlockPointerType(std::string& Str, QualType Type);
291 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
292 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
293 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
294 void RewriteTypeOfDecl(VarDecl *VD);
295 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
296
297 // Expression Rewriting.
298 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
299 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
300 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
301 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
302 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
303 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
304 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
305 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
306 void RewriteTryReturnStmts(Stmt *S);
307 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
308 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
309 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
310 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
311 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
312 SourceLocation OrigEnd);
313 Stmt *RewriteBreakStmt(BreakStmt *S);
314 Stmt *RewriteContinueStmt(ContinueStmt *S);
315 void RewriteCastExpr(CStyleCastExpr *CE);
316
317 // Block rewriting.
318 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
319
320 // Block specific rewrite rules.
321 void RewriteBlockPointerDecl(NamedDecl *VD);
322 void RewriteByRefVar(VarDecl *VD);
323 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
324 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
325 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
326
327 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
328 std::string &Result);
329
330 virtual void Initialize(ASTContext &context);
331
332 // Misc. AST transformation routines. Somtimes they end up calling
333 // rewriting routines on the new ASTs.
334 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
335 Expr **args, unsigned nargs,
336 SourceLocation StartLoc=SourceLocation(),
337 SourceLocation EndLoc=SourceLocation());
338
339 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
340 SourceLocation StartLoc=SourceLocation(),
341 SourceLocation EndLoc=SourceLocation());
342
343 void SynthCountByEnumWithState(std::string &buf);
344 void SynthMsgSendFunctionDecl();
345 void SynthMsgSendSuperFunctionDecl();
346 void SynthMsgSendStretFunctionDecl();
347 void SynthMsgSendFpretFunctionDecl();
348 void SynthMsgSendSuperStretFunctionDecl();
349 void SynthGetClassFunctionDecl();
350 void SynthGetMetaClassFunctionDecl();
351 void SynthGetSuperClassFunctionDecl();
352 void SynthSelGetUidFunctionDecl();
353 void SynthSuperContructorFunctionDecl();
354
355 // Rewriting metadata
356 template<typename MethodIterator>
357 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
358 MethodIterator MethodEnd,
359 bool IsInstanceMethod,
360 StringRef prefix,
361 StringRef ClassName,
362 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000363 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
364 std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000365 virtual void RewriteObjCProtocolListMetaData(
366 const ObjCList<ObjCProtocolDecl> &Prots,
367 StringRef prefix, StringRef ClassName, std::string &Result);
368 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
369 std::string &Result);
370 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
371 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
372 std::string &Result);
373
374 // Rewriting ivar
375 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
376 std::string &Result);
377 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
378
379
380 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
381 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
382 StringRef funcName, std::string Tag);
383 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
384 StringRef funcName, std::string Tag);
385 std::string SynthesizeBlockImpl(BlockExpr *CE,
386 std::string Tag, std::string Desc);
387 std::string SynthesizeBlockDescriptor(std::string DescTag,
388 std::string ImplTag,
389 int i, StringRef funcName,
390 unsigned hasCopy);
391 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
392 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
393 StringRef FunName);
394 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
395 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
396 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
397
398 // Misc. helper routines.
399 QualType getProtocolType();
400 void WarnAboutReturnGotoStmts(Stmt *S);
401 void HasReturnStmts(Stmt *S, bool &hasReturns);
402 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
403 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
404 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
405
406 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
407 void CollectBlockDeclRefInfo(BlockExpr *Exp);
408 void GetBlockDeclRefExprs(Stmt *S);
409 void GetInnerBlockDeclRefExprs(Stmt *S,
410 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
411 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
412
413 // We avoid calling Type::isBlockPointerType(), since it operates on the
414 // canonical type. We only care if the top-level type is a closure pointer.
415 bool isTopLevelBlockPointerType(QualType T) {
416 return isa<BlockPointerType>(T);
417 }
418
419 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
420 /// to a function pointer type and upon success, returns true; false
421 /// otherwise.
422 bool convertBlockPointerToFunctionPointer(QualType &T) {
423 if (isTopLevelBlockPointerType(T)) {
424 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
425 T = Context->getPointerType(BPT->getPointeeType());
426 return true;
427 }
428 return false;
429 }
430
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000431 bool convertObjCTypeToCStyleType(QualType &T);
432
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000433 bool needToScanForQualifiers(QualType T);
434 QualType getSuperStructType();
435 QualType getConstantStringStructType();
436 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
437 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
438
439 void convertToUnqualifiedObjCType(QualType &T) {
440 if (T->isObjCQualifiedIdType())
441 T = Context->getObjCIdType();
442 else if (T->isObjCQualifiedClassType())
443 T = Context->getObjCClassType();
444 else if (T->isObjCObjectPointerType() &&
445 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
446 if (const ObjCObjectPointerType * OBJPT =
447 T->getAsObjCInterfacePointerType()) {
448 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
449 T = QualType(IFaceT, 0);
450 T = Context->getPointerType(T);
451 }
452 }
453 }
454
455 // FIXME: This predicate seems like it would be useful to add to ASTContext.
456 bool isObjCType(QualType T) {
457 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
458 return false;
459
460 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
461
462 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
463 OCT == Context->getCanonicalType(Context->getObjCClassType()))
464 return true;
465
466 if (const PointerType *PT = OCT->getAs<PointerType>()) {
467 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
468 PT->getPointeeType()->isObjCQualifiedIdType())
469 return true;
470 }
471 return false;
472 }
473 bool PointerTypeTakesAnyBlockArguments(QualType QT);
474 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
475 void GetExtentOfArgList(const char *Name, const char *&LParen,
476 const char *&RParen);
477
478 void QuoteDoublequotes(std::string &From, std::string &To) {
479 for (unsigned i = 0; i < From.length(); i++) {
480 if (From[i] == '"')
481 To += "\\\"";
482 else
483 To += From[i];
484 }
485 }
486
487 QualType getSimpleFunctionType(QualType result,
488 const QualType *args,
489 unsigned numArgs,
490 bool variadic = false) {
491 if (result == Context->getObjCInstanceType())
492 result = Context->getObjCIdType();
493 FunctionProtoType::ExtProtoInfo fpi;
494 fpi.Variadic = variadic;
495 return Context->getFunctionType(result, args, numArgs, fpi);
496 }
497
498 // Helper function: create a CStyleCastExpr with trivial type source info.
499 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
500 CastKind Kind, Expr *E) {
501 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
502 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
503 SourceLocation(), SourceLocation());
504 }
505 };
506
507}
508
509void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
510 NamedDecl *D) {
511 if (const FunctionProtoType *fproto
512 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
513 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
514 E = fproto->arg_type_end(); I && (I != E); ++I)
515 if (isTopLevelBlockPointerType(*I)) {
516 // All the args are checked/rewritten. Don't call twice!
517 RewriteBlockPointerDecl(D);
518 break;
519 }
520 }
521}
522
523void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
524 const PointerType *PT = funcType->getAs<PointerType>();
525 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
526 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
527}
528
529static bool IsHeaderFile(const std::string &Filename) {
530 std::string::size_type DotPos = Filename.rfind('.');
531
532 if (DotPos == std::string::npos) {
533 // no file extension
534 return false;
535 }
536
537 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
538 // C header: .h
539 // C++ header: .hh or .H;
540 return Ext == "h" || Ext == "hh" || Ext == "H";
541}
542
543RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
544 DiagnosticsEngine &D, const LangOptions &LOpts,
545 bool silenceMacroWarn)
546 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
547 SilenceRewriteMacroWarning(silenceMacroWarn) {
548 IsHeader = IsHeaderFile(inFile);
549 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
550 "rewriting sub-expression within a macro (may not be correct)");
551 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
552 DiagnosticsEngine::Warning,
553 "rewriter doesn't support user-specified control flow semantics "
554 "for @try/@finally (code may not execute properly)");
555}
556
557ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
558 raw_ostream* OS,
559 DiagnosticsEngine &Diags,
560 const LangOptions &LOpts,
561 bool SilenceRewriteMacroWarning) {
562 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
563}
564
565void RewriteModernObjC::InitializeCommon(ASTContext &context) {
566 Context = &context;
567 SM = &Context->getSourceManager();
568 TUDecl = Context->getTranslationUnitDecl();
569 MsgSendFunctionDecl = 0;
570 MsgSendSuperFunctionDecl = 0;
571 MsgSendStretFunctionDecl = 0;
572 MsgSendSuperStretFunctionDecl = 0;
573 MsgSendFpretFunctionDecl = 0;
574 GetClassFunctionDecl = 0;
575 GetMetaClassFunctionDecl = 0;
576 GetSuperClassFunctionDecl = 0;
577 SelGetUidFunctionDecl = 0;
578 CFStringFunctionDecl = 0;
579 ConstantStringClassReference = 0;
580 NSStringRecord = 0;
581 CurMethodDef = 0;
582 CurFunctionDef = 0;
583 CurFunctionDeclToDeclareForBlock = 0;
584 GlobalVarDecl = 0;
585 SuperStructDecl = 0;
586 ProtocolTypeDecl = 0;
587 ConstantStringDecl = 0;
588 BcLabelCount = 0;
589 SuperContructorFunctionDecl = 0;
590 NumObjCStringLiterals = 0;
591 PropParentMap = 0;
592 CurrentBody = 0;
593 DisableReplaceStmt = false;
594 objc_impl_method = false;
595
596 // Get the ID and start/end of the main file.
597 MainFileID = SM->getMainFileID();
598 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
599 MainFileStart = MainBuf->getBufferStart();
600 MainFileEnd = MainBuf->getBufferEnd();
601
602 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
603}
604
605//===----------------------------------------------------------------------===//
606// Top Level Driver Code
607//===----------------------------------------------------------------------===//
608
609void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
610 if (Diags.hasErrorOccurred())
611 return;
612
613 // Two cases: either the decl could be in the main file, or it could be in a
614 // #included file. If the former, rewrite it now. If the later, check to see
615 // if we rewrote the #include/#import.
616 SourceLocation Loc = D->getLocation();
617 Loc = SM->getExpansionLoc(Loc);
618
619 // If this is for a builtin, ignore it.
620 if (Loc.isInvalid()) return;
621
622 // Look for built-in declarations that we need to refer during the rewrite.
623 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
624 RewriteFunctionDecl(FD);
625 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
626 // declared in <Foundation/NSString.h>
627 if (FVD->getName() == "_NSConstantStringClassReference") {
628 ConstantStringClassReference = FVD;
629 return;
630 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000631 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
632 RewriteCategoryDecl(CD);
633 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
634 if (PD->isThisDeclarationADefinition())
635 RewriteProtocolDecl(PD);
636 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
637 // Recurse into linkage specifications
638 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
639 DIEnd = LSD->decls_end();
640 DI != DIEnd; ) {
641 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
642 if (!IFace->isThisDeclarationADefinition()) {
643 SmallVector<Decl *, 8> DG;
644 SourceLocation StartLoc = IFace->getLocStart();
645 do {
646 if (isa<ObjCInterfaceDecl>(*DI) &&
647 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
648 StartLoc == (*DI)->getLocStart())
649 DG.push_back(*DI);
650 else
651 break;
652
653 ++DI;
654 } while (DI != DIEnd);
655 RewriteForwardClassDecl(DG);
656 continue;
657 }
658 }
659
660 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
661 if (!Proto->isThisDeclarationADefinition()) {
662 SmallVector<Decl *, 8> DG;
663 SourceLocation StartLoc = Proto->getLocStart();
664 do {
665 if (isa<ObjCProtocolDecl>(*DI) &&
666 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
667 StartLoc == (*DI)->getLocStart())
668 DG.push_back(*DI);
669 else
670 break;
671
672 ++DI;
673 } while (DI != DIEnd);
674 RewriteForwardProtocolDecl(DG);
675 continue;
676 }
677 }
678
679 HandleTopLevelSingleDecl(*DI);
680 ++DI;
681 }
682 }
683 // If we have a decl in the main file, see if we should rewrite it.
684 if (SM->isFromMainFile(Loc))
685 return HandleDeclInMainFile(D);
686}
687
688//===----------------------------------------------------------------------===//
689// Syntactic (non-AST) Rewriting Code
690//===----------------------------------------------------------------------===//
691
692void RewriteModernObjC::RewriteInclude() {
693 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
694 StringRef MainBuf = SM->getBufferData(MainFileID);
695 const char *MainBufStart = MainBuf.begin();
696 const char *MainBufEnd = MainBuf.end();
697 size_t ImportLen = strlen("import");
698
699 // Loop over the whole file, looking for includes.
700 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
701 if (*BufPtr == '#') {
702 if (++BufPtr == MainBufEnd)
703 return;
704 while (*BufPtr == ' ' || *BufPtr == '\t')
705 if (++BufPtr == MainBufEnd)
706 return;
707 if (!strncmp(BufPtr, "import", ImportLen)) {
708 // replace import with include
709 SourceLocation ImportLoc =
710 LocStart.getLocWithOffset(BufPtr-MainBufStart);
711 ReplaceText(ImportLoc, ImportLen, "include");
712 BufPtr += ImportLen;
713 }
714 }
715 }
716}
717
718static std::string getIvarAccessString(ObjCIvarDecl *OID) {
719 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
720 std::string S;
721 S = "((struct ";
722 S += ClassDecl->getIdentifier()->getName();
723 S += "_IMPL *)self)->";
724 S += OID->getName();
725 return S;
726}
727
728void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
729 ObjCImplementationDecl *IMD,
730 ObjCCategoryImplDecl *CID) {
731 static bool objcGetPropertyDefined = false;
732 static bool objcSetPropertyDefined = false;
733 SourceLocation startLoc = PID->getLocStart();
734 InsertText(startLoc, "// ");
735 const char *startBuf = SM->getCharacterData(startLoc);
736 assert((*startBuf == '@') && "bogus @synthesize location");
737 const char *semiBuf = strchr(startBuf, ';');
738 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
739 SourceLocation onePastSemiLoc =
740 startLoc.getLocWithOffset(semiBuf-startBuf+1);
741
742 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
743 return; // FIXME: is this correct?
744
745 // Generate the 'getter' function.
746 ObjCPropertyDecl *PD = PID->getPropertyDecl();
747 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
748
749 if (!OID)
750 return;
751 unsigned Attributes = PD->getPropertyAttributes();
752 if (!PD->getGetterMethodDecl()->isDefined()) {
753 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
754 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
755 ObjCPropertyDecl::OBJC_PR_copy));
756 std::string Getr;
757 if (GenGetProperty && !objcGetPropertyDefined) {
758 objcGetPropertyDefined = true;
759 // FIXME. Is this attribute correct in all cases?
760 Getr = "\nextern \"C\" __declspec(dllimport) "
761 "id objc_getProperty(id, SEL, long, bool);\n";
762 }
763 RewriteObjCMethodDecl(OID->getContainingInterface(),
764 PD->getGetterMethodDecl(), Getr);
765 Getr += "{ ";
766 // Synthesize an explicit cast to gain access to the ivar.
767 // See objc-act.c:objc_synthesize_new_getter() for details.
768 if (GenGetProperty) {
769 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
770 Getr += "typedef ";
771 const FunctionType *FPRetType = 0;
772 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
773 FPRetType);
774 Getr += " _TYPE";
775 if (FPRetType) {
776 Getr += ")"; // close the precedence "scope" for "*".
777
778 // Now, emit the argument types (if any).
779 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
780 Getr += "(";
781 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
782 if (i) Getr += ", ";
783 std::string ParamStr = FT->getArgType(i).getAsString(
784 Context->getPrintingPolicy());
785 Getr += ParamStr;
786 }
787 if (FT->isVariadic()) {
788 if (FT->getNumArgs()) Getr += ", ";
789 Getr += "...";
790 }
791 Getr += ")";
792 } else
793 Getr += "()";
794 }
795 Getr += ";\n";
796 Getr += "return (_TYPE)";
797 Getr += "objc_getProperty(self, _cmd, ";
798 RewriteIvarOffsetComputation(OID, Getr);
799 Getr += ", 1)";
800 }
801 else
802 Getr += "return " + getIvarAccessString(OID);
803 Getr += "; }";
804 InsertText(onePastSemiLoc, Getr);
805 }
806
807 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
808 return;
809
810 // Generate the 'setter' function.
811 std::string Setr;
812 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
813 ObjCPropertyDecl::OBJC_PR_copy);
814 if (GenSetProperty && !objcSetPropertyDefined) {
815 objcSetPropertyDefined = true;
816 // FIXME. Is this attribute correct in all cases?
817 Setr = "\nextern \"C\" __declspec(dllimport) "
818 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
819 }
820
821 RewriteObjCMethodDecl(OID->getContainingInterface(),
822 PD->getSetterMethodDecl(), Setr);
823 Setr += "{ ";
824 // Synthesize an explicit cast to initialize the ivar.
825 // See objc-act.c:objc_synthesize_new_setter() for details.
826 if (GenSetProperty) {
827 Setr += "objc_setProperty (self, _cmd, ";
828 RewriteIvarOffsetComputation(OID, Setr);
829 Setr += ", (id)";
830 Setr += PD->getName();
831 Setr += ", ";
832 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
833 Setr += "0, ";
834 else
835 Setr += "1, ";
836 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
837 Setr += "1)";
838 else
839 Setr += "0)";
840 }
841 else {
842 Setr += getIvarAccessString(OID) + " = ";
843 Setr += PD->getName();
844 }
845 Setr += "; }";
846 InsertText(onePastSemiLoc, Setr);
847}
848
849static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
850 std::string &typedefString) {
851 typedefString += "#ifndef _REWRITER_typedef_";
852 typedefString += ForwardDecl->getNameAsString();
853 typedefString += "\n";
854 typedefString += "#define _REWRITER_typedef_";
855 typedefString += ForwardDecl->getNameAsString();
856 typedefString += "\n";
857 typedefString += "typedef struct objc_object ";
858 typedefString += ForwardDecl->getNameAsString();
859 typedefString += ";\n#endif\n";
860}
861
862void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
863 const std::string &typedefString) {
864 SourceLocation startLoc = ClassDecl->getLocStart();
865 const char *startBuf = SM->getCharacterData(startLoc);
866 const char *semiPtr = strchr(startBuf, ';');
867 // Replace the @class with typedefs corresponding to the classes.
868 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
869}
870
871void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
872 std::string typedefString;
873 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
874 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
875 if (I == D.begin()) {
876 // Translate to typedef's that forward reference structs with the same name
877 // as the class. As a convenience, we include the original declaration
878 // as a comment.
879 typedefString += "// @class ";
880 typedefString += ForwardDecl->getNameAsString();
881 typedefString += ";\n";
882 }
883 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
884 }
885 DeclGroupRef::iterator I = D.begin();
886 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
887}
888
889void RewriteModernObjC::RewriteForwardClassDecl(
890 const llvm::SmallVector<Decl*, 8> &D) {
891 std::string typedefString;
892 for (unsigned i = 0; i < D.size(); i++) {
893 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
894 if (i == 0) {
895 typedefString += "// @class ";
896 typedefString += ForwardDecl->getNameAsString();
897 typedefString += ";\n";
898 }
899 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
900 }
901 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
902}
903
904void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
905 // When method is a synthesized one, such as a getter/setter there is
906 // nothing to rewrite.
907 if (Method->isImplicit())
908 return;
909 SourceLocation LocStart = Method->getLocStart();
910 SourceLocation LocEnd = Method->getLocEnd();
911
912 if (SM->getExpansionLineNumber(LocEnd) >
913 SM->getExpansionLineNumber(LocStart)) {
914 InsertText(LocStart, "#if 0\n");
915 ReplaceText(LocEnd, 1, ";\n#endif\n");
916 } else {
917 InsertText(LocStart, "// ");
918 }
919}
920
921void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
922 SourceLocation Loc = prop->getAtLoc();
923
924 ReplaceText(Loc, 0, "// ");
925 // FIXME: handle properties that are declared across multiple lines.
926}
927
928void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
929 SourceLocation LocStart = CatDecl->getLocStart();
930
931 // FIXME: handle category headers that are declared across multiple lines.
932 ReplaceText(LocStart, 0, "// ");
933
934 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
935 E = CatDecl->prop_end(); I != E; ++I)
936 RewriteProperty(*I);
937
938 for (ObjCCategoryDecl::instmeth_iterator
939 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
940 I != E; ++I)
941 RewriteMethodDeclaration(*I);
942 for (ObjCCategoryDecl::classmeth_iterator
943 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
944 I != E; ++I)
945 RewriteMethodDeclaration(*I);
946
947 // Lastly, comment out the @end.
948 ReplaceText(CatDecl->getAtEndRange().getBegin(),
949 strlen("@end"), "/* @end */");
950}
951
952void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
953 SourceLocation LocStart = PDecl->getLocStart();
954 assert(PDecl->isThisDeclarationADefinition());
955
956 // FIXME: handle protocol headers that are declared across multiple lines.
957 ReplaceText(LocStart, 0, "// ");
958
959 for (ObjCProtocolDecl::instmeth_iterator
960 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
961 I != E; ++I)
962 RewriteMethodDeclaration(*I);
963 for (ObjCProtocolDecl::classmeth_iterator
964 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
965 I != E; ++I)
966 RewriteMethodDeclaration(*I);
967
968 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
969 E = PDecl->prop_end(); I != E; ++I)
970 RewriteProperty(*I);
971
972 // Lastly, comment out the @end.
973 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
974 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
975
976 // Must comment out @optional/@required
977 const char *startBuf = SM->getCharacterData(LocStart);
978 const char *endBuf = SM->getCharacterData(LocEnd);
979 for (const char *p = startBuf; p < endBuf; p++) {
980 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
981 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
982 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
983
984 }
985 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
986 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
987 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
988
989 }
990 }
991}
992
993void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
994 SourceLocation LocStart = (*D.begin())->getLocStart();
995 if (LocStart.isInvalid())
996 llvm_unreachable("Invalid SourceLocation");
997 // FIXME: handle forward protocol that are declared across multiple lines.
998 ReplaceText(LocStart, 0, "// ");
999}
1000
1001void
1002RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1003 SourceLocation LocStart = DG[0]->getLocStart();
1004 if (LocStart.isInvalid())
1005 llvm_unreachable("Invalid SourceLocation");
1006 // FIXME: handle forward protocol that are declared across multiple lines.
1007 ReplaceText(LocStart, 0, "// ");
1008}
1009
1010void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1011 const FunctionType *&FPRetType) {
1012 if (T->isObjCQualifiedIdType())
1013 ResultStr += "id";
1014 else if (T->isFunctionPointerType() ||
1015 T->isBlockPointerType()) {
1016 // needs special handling, since pointer-to-functions have special
1017 // syntax (where a decaration models use).
1018 QualType retType = T;
1019 QualType PointeeTy;
1020 if (const PointerType* PT = retType->getAs<PointerType>())
1021 PointeeTy = PT->getPointeeType();
1022 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1023 PointeeTy = BPT->getPointeeType();
1024 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1025 ResultStr += FPRetType->getResultType().getAsString(
1026 Context->getPrintingPolicy());
1027 ResultStr += "(*";
1028 }
1029 } else
1030 ResultStr += T.getAsString(Context->getPrintingPolicy());
1031}
1032
1033void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1034 ObjCMethodDecl *OMD,
1035 std::string &ResultStr) {
1036 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1037 const FunctionType *FPRetType = 0;
1038 ResultStr += "\nstatic ";
1039 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1040 ResultStr += " ";
1041
1042 // Unique method name
1043 std::string NameStr;
1044
1045 if (OMD->isInstanceMethod())
1046 NameStr += "_I_";
1047 else
1048 NameStr += "_C_";
1049
1050 NameStr += IDecl->getNameAsString();
1051 NameStr += "_";
1052
1053 if (ObjCCategoryImplDecl *CID =
1054 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1055 NameStr += CID->getNameAsString();
1056 NameStr += "_";
1057 }
1058 // Append selector names, replacing ':' with '_'
1059 {
1060 std::string selString = OMD->getSelector().getAsString();
1061 int len = selString.size();
1062 for (int i = 0; i < len; i++)
1063 if (selString[i] == ':')
1064 selString[i] = '_';
1065 NameStr += selString;
1066 }
1067 // Remember this name for metadata emission
1068 MethodInternalNames[OMD] = NameStr;
1069 ResultStr += NameStr;
1070
1071 // Rewrite arguments
1072 ResultStr += "(";
1073
1074 // invisible arguments
1075 if (OMD->isInstanceMethod()) {
1076 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1077 selfTy = Context->getPointerType(selfTy);
1078 if (!LangOpts.MicrosoftExt) {
1079 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1080 ResultStr += "struct ";
1081 }
1082 // When rewriting for Microsoft, explicitly omit the structure name.
1083 ResultStr += IDecl->getNameAsString();
1084 ResultStr += " *";
1085 }
1086 else
1087 ResultStr += Context->getObjCClassType().getAsString(
1088 Context->getPrintingPolicy());
1089
1090 ResultStr += " self, ";
1091 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1092 ResultStr += " _cmd";
1093
1094 // Method arguments.
1095 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1096 E = OMD->param_end(); PI != E; ++PI) {
1097 ParmVarDecl *PDecl = *PI;
1098 ResultStr += ", ";
1099 if (PDecl->getType()->isObjCQualifiedIdType()) {
1100 ResultStr += "id ";
1101 ResultStr += PDecl->getNameAsString();
1102 } else {
1103 std::string Name = PDecl->getNameAsString();
1104 QualType QT = PDecl->getType();
1105 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1106 if (convertBlockPointerToFunctionPointer(QT))
1107 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1108 else
1109 PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy());
1110 ResultStr += Name;
1111 }
1112 }
1113 if (OMD->isVariadic())
1114 ResultStr += ", ...";
1115 ResultStr += ") ";
1116
1117 if (FPRetType) {
1118 ResultStr += ")"; // close the precedence "scope" for "*".
1119
1120 // Now, emit the argument types (if any).
1121 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1122 ResultStr += "(";
1123 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1124 if (i) ResultStr += ", ";
1125 std::string ParamStr = FT->getArgType(i).getAsString(
1126 Context->getPrintingPolicy());
1127 ResultStr += ParamStr;
1128 }
1129 if (FT->isVariadic()) {
1130 if (FT->getNumArgs()) ResultStr += ", ";
1131 ResultStr += "...";
1132 }
1133 ResultStr += ")";
1134 } else {
1135 ResultStr += "()";
1136 }
1137 }
1138}
1139void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1140 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1141 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1142
1143 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
1144
1145 for (ObjCCategoryImplDecl::instmeth_iterator
1146 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1147 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1148 I != E; ++I) {
1149 std::string ResultStr;
1150 ObjCMethodDecl *OMD = *I;
1151 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1152 SourceLocation LocStart = OMD->getLocStart();
1153 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1154
1155 const char *startBuf = SM->getCharacterData(LocStart);
1156 const char *endBuf = SM->getCharacterData(LocEnd);
1157 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1158 }
1159
1160 for (ObjCCategoryImplDecl::classmeth_iterator
1161 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1162 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1163 I != E; ++I) {
1164 std::string ResultStr;
1165 ObjCMethodDecl *OMD = *I;
1166 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1167 SourceLocation LocStart = OMD->getLocStart();
1168 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1169
1170 const char *startBuf = SM->getCharacterData(LocStart);
1171 const char *endBuf = SM->getCharacterData(LocEnd);
1172 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1173 }
1174 for (ObjCCategoryImplDecl::propimpl_iterator
1175 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1176 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1177 I != E; ++I) {
1178 RewritePropertyImplDecl(*I, IMD, CID);
1179 }
1180
1181 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1182}
1183
1184void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001185 // Do not synthesize more than once.
1186 if (ObjCSynthesizedStructs.count(ClassDecl))
1187 return;
1188 // Make sure super class's are written before current class is written.
1189 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1190 while (SuperClass) {
1191 RewriteInterfaceDecl(SuperClass);
1192 SuperClass = SuperClass->getSuperClass();
1193 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001194 std::string ResultStr;
1195 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
1196 // we haven't seen a forward decl - generate a typedef.
1197 ResultStr = "#ifndef _REWRITER_typedef_";
1198 ResultStr += ClassDecl->getNameAsString();
1199 ResultStr += "\n";
1200 ResultStr += "#define _REWRITER_typedef_";
1201 ResultStr += ClassDecl->getNameAsString();
1202 ResultStr += "\n";
1203 ResultStr += "typedef struct objc_object ";
1204 ResultStr += ClassDecl->getNameAsString();
1205 ResultStr += ";\n#endif\n";
1206 // Mark this typedef as having been generated.
1207 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
1208 }
1209 RewriteObjCInternalStruct(ClassDecl, ResultStr);
1210
1211 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
1212 E = ClassDecl->prop_end(); I != E; ++I)
1213 RewriteProperty(*I);
1214 for (ObjCInterfaceDecl::instmeth_iterator
1215 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
1216 I != E; ++I)
1217 RewriteMethodDeclaration(*I);
1218 for (ObjCInterfaceDecl::classmeth_iterator
1219 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
1220 I != E; ++I)
1221 RewriteMethodDeclaration(*I);
1222
1223 // Lastly, comment out the @end.
1224 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1225 "/* @end */");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001226 // Mark this struct as having been generated.
1227 if (!ObjCSynthesizedStructs.insert(ClassDecl))
1228 llvm_unreachable("struct already synthesize- RewriteInterfaceDecl");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001229}
1230
1231Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1232 SourceRange OldRange = PseudoOp->getSourceRange();
1233
1234 // We just magically know some things about the structure of this
1235 // expression.
1236 ObjCMessageExpr *OldMsg =
1237 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1238 PseudoOp->getNumSemanticExprs() - 1));
1239
1240 // Because the rewriter doesn't allow us to rewrite rewritten code,
1241 // we need to suppress rewriting the sub-statements.
1242 Expr *Base, *RHS;
1243 {
1244 DisableReplaceStmtScope S(*this);
1245
1246 // Rebuild the base expression if we have one.
1247 Base = 0;
1248 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1249 Base = OldMsg->getInstanceReceiver();
1250 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1251 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1252 }
1253
1254 // Rebuild the RHS.
1255 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1256 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1257 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1258 }
1259
1260 // TODO: avoid this copy.
1261 SmallVector<SourceLocation, 1> SelLocs;
1262 OldMsg->getSelectorLocs(SelLocs);
1263
1264 ObjCMessageExpr *NewMsg = 0;
1265 switch (OldMsg->getReceiverKind()) {
1266 case ObjCMessageExpr::Class:
1267 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1268 OldMsg->getValueKind(),
1269 OldMsg->getLeftLoc(),
1270 OldMsg->getClassReceiverTypeInfo(),
1271 OldMsg->getSelector(),
1272 SelLocs,
1273 OldMsg->getMethodDecl(),
1274 RHS,
1275 OldMsg->getRightLoc(),
1276 OldMsg->isImplicit());
1277 break;
1278
1279 case ObjCMessageExpr::Instance:
1280 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1281 OldMsg->getValueKind(),
1282 OldMsg->getLeftLoc(),
1283 Base,
1284 OldMsg->getSelector(),
1285 SelLocs,
1286 OldMsg->getMethodDecl(),
1287 RHS,
1288 OldMsg->getRightLoc(),
1289 OldMsg->isImplicit());
1290 break;
1291
1292 case ObjCMessageExpr::SuperClass:
1293 case ObjCMessageExpr::SuperInstance:
1294 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1295 OldMsg->getValueKind(),
1296 OldMsg->getLeftLoc(),
1297 OldMsg->getSuperLoc(),
1298 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1299 OldMsg->getSuperType(),
1300 OldMsg->getSelector(),
1301 SelLocs,
1302 OldMsg->getMethodDecl(),
1303 RHS,
1304 OldMsg->getRightLoc(),
1305 OldMsg->isImplicit());
1306 break;
1307 }
1308
1309 Stmt *Replacement = SynthMessageExpr(NewMsg);
1310 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1311 return Replacement;
1312}
1313
1314Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1315 SourceRange OldRange = PseudoOp->getSourceRange();
1316
1317 // We just magically know some things about the structure of this
1318 // expression.
1319 ObjCMessageExpr *OldMsg =
1320 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1321
1322 // Because the rewriter doesn't allow us to rewrite rewritten code,
1323 // we need to suppress rewriting the sub-statements.
1324 Expr *Base = 0;
1325 {
1326 DisableReplaceStmtScope S(*this);
1327
1328 // Rebuild the base expression if we have one.
1329 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1330 Base = OldMsg->getInstanceReceiver();
1331 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1332 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1333 }
1334 }
1335
1336 // Intentionally empty.
1337 SmallVector<SourceLocation, 1> SelLocs;
1338 SmallVector<Expr*, 1> Args;
1339
1340 ObjCMessageExpr *NewMsg = 0;
1341 switch (OldMsg->getReceiverKind()) {
1342 case ObjCMessageExpr::Class:
1343 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1344 OldMsg->getValueKind(),
1345 OldMsg->getLeftLoc(),
1346 OldMsg->getClassReceiverTypeInfo(),
1347 OldMsg->getSelector(),
1348 SelLocs,
1349 OldMsg->getMethodDecl(),
1350 Args,
1351 OldMsg->getRightLoc(),
1352 OldMsg->isImplicit());
1353 break;
1354
1355 case ObjCMessageExpr::Instance:
1356 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1357 OldMsg->getValueKind(),
1358 OldMsg->getLeftLoc(),
1359 Base,
1360 OldMsg->getSelector(),
1361 SelLocs,
1362 OldMsg->getMethodDecl(),
1363 Args,
1364 OldMsg->getRightLoc(),
1365 OldMsg->isImplicit());
1366 break;
1367
1368 case ObjCMessageExpr::SuperClass:
1369 case ObjCMessageExpr::SuperInstance:
1370 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1371 OldMsg->getValueKind(),
1372 OldMsg->getLeftLoc(),
1373 OldMsg->getSuperLoc(),
1374 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1375 OldMsg->getSuperType(),
1376 OldMsg->getSelector(),
1377 SelLocs,
1378 OldMsg->getMethodDecl(),
1379 Args,
1380 OldMsg->getRightLoc(),
1381 OldMsg->isImplicit());
1382 break;
1383 }
1384
1385 Stmt *Replacement = SynthMessageExpr(NewMsg);
1386 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1387 return Replacement;
1388}
1389
1390/// SynthCountByEnumWithState - To print:
1391/// ((unsigned int (*)
1392/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1393/// (void *)objc_msgSend)((id)l_collection,
1394/// sel_registerName(
1395/// "countByEnumeratingWithState:objects:count:"),
1396/// &enumState,
1397/// (id *)__rw_items, (unsigned int)16)
1398///
1399void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1400 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1401 "id *, unsigned int))(void *)objc_msgSend)";
1402 buf += "\n\t\t";
1403 buf += "((id)l_collection,\n\t\t";
1404 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1405 buf += "\n\t\t";
1406 buf += "&enumState, "
1407 "(id *)__rw_items, (unsigned int)16)";
1408}
1409
1410/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1411/// statement to exit to its outer synthesized loop.
1412///
1413Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1414 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1415 return S;
1416 // replace break with goto __break_label
1417 std::string buf;
1418
1419 SourceLocation startLoc = S->getLocStart();
1420 buf = "goto __break_label_";
1421 buf += utostr(ObjCBcLabelNo.back());
1422 ReplaceText(startLoc, strlen("break"), buf);
1423
1424 return 0;
1425}
1426
1427/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1428/// statement to continue with its inner synthesized loop.
1429///
1430Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1431 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1432 return S;
1433 // replace continue with goto __continue_label
1434 std::string buf;
1435
1436 SourceLocation startLoc = S->getLocStart();
1437 buf = "goto __continue_label_";
1438 buf += utostr(ObjCBcLabelNo.back());
1439 ReplaceText(startLoc, strlen("continue"), buf);
1440
1441 return 0;
1442}
1443
1444/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1445/// It rewrites:
1446/// for ( type elem in collection) { stmts; }
1447
1448/// Into:
1449/// {
1450/// type elem;
1451/// struct __objcFastEnumerationState enumState = { 0 };
1452/// id __rw_items[16];
1453/// id l_collection = (id)collection;
1454/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1455/// objects:__rw_items count:16];
1456/// if (limit) {
1457/// unsigned long startMutations = *enumState.mutationsPtr;
1458/// do {
1459/// unsigned long counter = 0;
1460/// do {
1461/// if (startMutations != *enumState.mutationsPtr)
1462/// objc_enumerationMutation(l_collection);
1463/// elem = (type)enumState.itemsPtr[counter++];
1464/// stmts;
1465/// __continue_label: ;
1466/// } while (counter < limit);
1467/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1468/// objects:__rw_items count:16]);
1469/// elem = nil;
1470/// __break_label: ;
1471/// }
1472/// else
1473/// elem = nil;
1474/// }
1475///
1476Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1477 SourceLocation OrigEnd) {
1478 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1479 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1480 "ObjCForCollectionStmt Statement stack mismatch");
1481 assert(!ObjCBcLabelNo.empty() &&
1482 "ObjCForCollectionStmt - Label No stack empty");
1483
1484 SourceLocation startLoc = S->getLocStart();
1485 const char *startBuf = SM->getCharacterData(startLoc);
1486 StringRef elementName;
1487 std::string elementTypeAsString;
1488 std::string buf;
1489 buf = "\n{\n\t";
1490 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1491 // type elem;
1492 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1493 QualType ElementType = cast<ValueDecl>(D)->getType();
1494 if (ElementType->isObjCQualifiedIdType() ||
1495 ElementType->isObjCQualifiedInterfaceType())
1496 // Simply use 'id' for all qualified types.
1497 elementTypeAsString = "id";
1498 else
1499 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1500 buf += elementTypeAsString;
1501 buf += " ";
1502 elementName = D->getName();
1503 buf += elementName;
1504 buf += ";\n\t";
1505 }
1506 else {
1507 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1508 elementName = DR->getDecl()->getName();
1509 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1510 if (VD->getType()->isObjCQualifiedIdType() ||
1511 VD->getType()->isObjCQualifiedInterfaceType())
1512 // Simply use 'id' for all qualified types.
1513 elementTypeAsString = "id";
1514 else
1515 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1516 }
1517
1518 // struct __objcFastEnumerationState enumState = { 0 };
1519 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1520 // id __rw_items[16];
1521 buf += "id __rw_items[16];\n\t";
1522 // id l_collection = (id)
1523 buf += "id l_collection = (id)";
1524 // Find start location of 'collection' the hard way!
1525 const char *startCollectionBuf = startBuf;
1526 startCollectionBuf += 3; // skip 'for'
1527 startCollectionBuf = strchr(startCollectionBuf, '(');
1528 startCollectionBuf++; // skip '('
1529 // find 'in' and skip it.
1530 while (*startCollectionBuf != ' ' ||
1531 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1532 (*(startCollectionBuf+3) != ' ' &&
1533 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1534 startCollectionBuf++;
1535 startCollectionBuf += 3;
1536
1537 // Replace: "for (type element in" with string constructed thus far.
1538 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1539 // Replace ')' in for '(' type elem in collection ')' with ';'
1540 SourceLocation rightParenLoc = S->getRParenLoc();
1541 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1542 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1543 buf = ";\n\t";
1544
1545 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1546 // objects:__rw_items count:16];
1547 // which is synthesized into:
1548 // unsigned int limit =
1549 // ((unsigned int (*)
1550 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1551 // (void *)objc_msgSend)((id)l_collection,
1552 // sel_registerName(
1553 // "countByEnumeratingWithState:objects:count:"),
1554 // (struct __objcFastEnumerationState *)&state,
1555 // (id *)__rw_items, (unsigned int)16);
1556 buf += "unsigned long limit =\n\t\t";
1557 SynthCountByEnumWithState(buf);
1558 buf += ";\n\t";
1559 /// if (limit) {
1560 /// unsigned long startMutations = *enumState.mutationsPtr;
1561 /// do {
1562 /// unsigned long counter = 0;
1563 /// do {
1564 /// if (startMutations != *enumState.mutationsPtr)
1565 /// objc_enumerationMutation(l_collection);
1566 /// elem = (type)enumState.itemsPtr[counter++];
1567 buf += "if (limit) {\n\t";
1568 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1569 buf += "do {\n\t\t";
1570 buf += "unsigned long counter = 0;\n\t\t";
1571 buf += "do {\n\t\t\t";
1572 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1573 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1574 buf += elementName;
1575 buf += " = (";
1576 buf += elementTypeAsString;
1577 buf += ")enumState.itemsPtr[counter++];";
1578 // Replace ')' in for '(' type elem in collection ')' with all of these.
1579 ReplaceText(lparenLoc, 1, buf);
1580
1581 /// __continue_label: ;
1582 /// } while (counter < limit);
1583 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1584 /// objects:__rw_items count:16]);
1585 /// elem = nil;
1586 /// __break_label: ;
1587 /// }
1588 /// else
1589 /// elem = nil;
1590 /// }
1591 ///
1592 buf = ";\n\t";
1593 buf += "__continue_label_";
1594 buf += utostr(ObjCBcLabelNo.back());
1595 buf += ": ;";
1596 buf += "\n\t\t";
1597 buf += "} while (counter < limit);\n\t";
1598 buf += "} while (limit = ";
1599 SynthCountByEnumWithState(buf);
1600 buf += ");\n\t";
1601 buf += elementName;
1602 buf += " = ((";
1603 buf += elementTypeAsString;
1604 buf += ")0);\n\t";
1605 buf += "__break_label_";
1606 buf += utostr(ObjCBcLabelNo.back());
1607 buf += ": ;\n\t";
1608 buf += "}\n\t";
1609 buf += "else\n\t\t";
1610 buf += elementName;
1611 buf += " = ((";
1612 buf += elementTypeAsString;
1613 buf += ")0);\n\t";
1614 buf += "}\n";
1615
1616 // Insert all these *after* the statement body.
1617 // FIXME: If this should support Obj-C++, support CXXTryStmt
1618 if (isa<CompoundStmt>(S->getBody())) {
1619 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1620 InsertText(endBodyLoc, buf);
1621 } else {
1622 /* Need to treat single statements specially. For example:
1623 *
1624 * for (A *a in b) if (stuff()) break;
1625 * for (A *a in b) xxxyy;
1626 *
1627 * The following code simply scans ahead to the semi to find the actual end.
1628 */
1629 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1630 const char *semiBuf = strchr(stmtBuf, ';');
1631 assert(semiBuf && "Can't find ';'");
1632 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1633 InsertText(endBodyLoc, buf);
1634 }
1635 Stmts.pop_back();
1636 ObjCBcLabelNo.pop_back();
1637 return 0;
1638}
1639
1640/// RewriteObjCSynchronizedStmt -
1641/// This routine rewrites @synchronized(expr) stmt;
1642/// into:
1643/// objc_sync_enter(expr);
1644/// @try stmt @finally { objc_sync_exit(expr); }
1645///
1646Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1647 // Get the start location and compute the semi location.
1648 SourceLocation startLoc = S->getLocStart();
1649 const char *startBuf = SM->getCharacterData(startLoc);
1650
1651 assert((*startBuf == '@') && "bogus @synchronized location");
1652
1653 std::string buf;
1654 buf = "objc_sync_enter((id)";
1655 const char *lparenBuf = startBuf;
1656 while (*lparenBuf != '(') lparenBuf++;
1657 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1658 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1659 // the sync expression is typically a message expression that's already
1660 // been rewritten! (which implies the SourceLocation's are invalid).
1661 SourceLocation endLoc = S->getSynchBody()->getLocStart();
1662 const char *endBuf = SM->getCharacterData(endLoc);
1663 while (*endBuf != ')') endBuf--;
1664 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
1665 buf = ");\n";
1666 // declare a new scope with two variables, _stack and _rethrow.
1667 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1668 buf += "int buf[18/*32-bit i386*/];\n";
1669 buf += "char *pointers[4];} _stack;\n";
1670 buf += "id volatile _rethrow = 0;\n";
1671 buf += "objc_exception_try_enter(&_stack);\n";
1672 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1673 ReplaceText(rparenLoc, 1, buf);
1674 startLoc = S->getSynchBody()->getLocEnd();
1675 startBuf = SM->getCharacterData(startLoc);
1676
1677 assert((*startBuf == '}') && "bogus @synchronized block");
1678 SourceLocation lastCurlyLoc = startLoc;
1679 buf = "}\nelse {\n";
1680 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1681 buf += "}\n";
1682 buf += "{ /* implicit finally clause */\n";
1683 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1684
1685 std::string syncBuf;
1686 syncBuf += " objc_sync_exit(";
1687
1688 Expr *syncExpr = S->getSynchExpr();
1689 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1690 ? CK_BitCast :
1691 syncExpr->getType()->isBlockPointerType()
1692 ? CK_BlockPointerToObjCPointerCast
1693 : CK_CPointerToObjCPointerCast;
1694 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1695 CK, syncExpr);
1696 std::string syncExprBufS;
1697 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
1698 syncExpr->printPretty(syncExprBuf, *Context, 0,
1699 PrintingPolicy(LangOpts));
1700 syncBuf += syncExprBuf.str();
1701 syncBuf += ");";
1702
1703 buf += syncBuf;
1704 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
1705 buf += "}\n";
1706 buf += "}";
1707
1708 ReplaceText(lastCurlyLoc, 1, buf);
1709
1710 bool hasReturns = false;
1711 HasReturnStmts(S->getSynchBody(), hasReturns);
1712 if (hasReturns)
1713 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1714
1715 return 0;
1716}
1717
1718void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1719{
1720 // Perform a bottom up traversal of all children.
1721 for (Stmt::child_range CI = S->children(); CI; ++CI)
1722 if (*CI)
1723 WarnAboutReturnGotoStmts(*CI);
1724
1725 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1726 Diags.Report(Context->getFullLoc(S->getLocStart()),
1727 TryFinallyContainsReturnDiag);
1728 }
1729 return;
1730}
1731
1732void RewriteModernObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1733{
1734 // Perform a bottom up traversal of all children.
1735 for (Stmt::child_range CI = S->children(); CI; ++CI)
1736 if (*CI)
1737 HasReturnStmts(*CI, hasReturns);
1738
1739 if (isa<ReturnStmt>(S))
1740 hasReturns = true;
1741 return;
1742}
1743
1744void RewriteModernObjC::RewriteTryReturnStmts(Stmt *S) {
1745 // Perform a bottom up traversal of all children.
1746 for (Stmt::child_range CI = S->children(); CI; ++CI)
1747 if (*CI) {
1748 RewriteTryReturnStmts(*CI);
1749 }
1750 if (isa<ReturnStmt>(S)) {
1751 SourceLocation startLoc = S->getLocStart();
1752 const char *startBuf = SM->getCharacterData(startLoc);
1753
1754 const char *semiBuf = strchr(startBuf, ';');
1755 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1756 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1757
1758 std::string buf;
1759 buf = "{ objc_exception_try_exit(&_stack); return";
1760
1761 ReplaceText(startLoc, 6, buf);
1762 InsertText(onePastSemiLoc, "}");
1763 }
1764 return;
1765}
1766
1767void RewriteModernObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1768 // Perform a bottom up traversal of all children.
1769 for (Stmt::child_range CI = S->children(); CI; ++CI)
1770 if (*CI) {
1771 RewriteSyncReturnStmts(*CI, syncExitBuf);
1772 }
1773 if (isa<ReturnStmt>(S)) {
1774 SourceLocation startLoc = S->getLocStart();
1775 const char *startBuf = SM->getCharacterData(startLoc);
1776
1777 const char *semiBuf = strchr(startBuf, ';');
1778 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1779 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1780
1781 std::string buf;
1782 buf = "{ objc_exception_try_exit(&_stack);";
1783 buf += syncExitBuf;
1784 buf += " return";
1785
1786 ReplaceText(startLoc, 6, buf);
1787 InsertText(onePastSemiLoc, "}");
1788 }
1789 return;
1790}
1791
1792Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1793 // Get the start location and compute the semi location.
1794 SourceLocation startLoc = S->getLocStart();
1795 const char *startBuf = SM->getCharacterData(startLoc);
1796
1797 assert((*startBuf == '@') && "bogus @try location");
1798
1799 std::string buf;
1800 // declare a new scope with two variables, _stack and _rethrow.
1801 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1802 buf += "int buf[18/*32-bit i386*/];\n";
1803 buf += "char *pointers[4];} _stack;\n";
1804 buf += "id volatile _rethrow = 0;\n";
1805 buf += "objc_exception_try_enter(&_stack);\n";
1806 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1807
1808 ReplaceText(startLoc, 4, buf);
1809
1810 startLoc = S->getTryBody()->getLocEnd();
1811 startBuf = SM->getCharacterData(startLoc);
1812
1813 assert((*startBuf == '}') && "bogus @try block");
1814
1815 SourceLocation lastCurlyLoc = startLoc;
1816 if (S->getNumCatchStmts()) {
1817 startLoc = startLoc.getLocWithOffset(1);
1818 buf = " /* @catch begin */ else {\n";
1819 buf += " id _caught = objc_exception_extract(&_stack);\n";
1820 buf += " objc_exception_try_enter (&_stack);\n";
1821 buf += " if (_setjmp(_stack.buf))\n";
1822 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1823 buf += " else { /* @catch continue */";
1824
1825 InsertText(startLoc, buf);
1826 } else { /* no catch list */
1827 buf = "}\nelse {\n";
1828 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1829 buf += "}";
1830 ReplaceText(lastCurlyLoc, 1, buf);
1831 }
1832 Stmt *lastCatchBody = 0;
1833 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1834 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1835 VarDecl *catchDecl = Catch->getCatchParamDecl();
1836
1837 if (I == 0)
1838 buf = "if ("; // we are generating code for the first catch clause
1839 else
1840 buf = "else if (";
1841 startLoc = Catch->getLocStart();
1842 startBuf = SM->getCharacterData(startLoc);
1843
1844 assert((*startBuf == '@') && "bogus @catch location");
1845
1846 const char *lParenLoc = strchr(startBuf, '(');
1847
1848 if (Catch->hasEllipsis()) {
1849 // Now rewrite the body...
1850 lastCatchBody = Catch->getCatchBody();
1851 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1852 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1853 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
1854 "bogus @catch paren location");
1855 assert((*bodyBuf == '{') && "bogus @catch body location");
1856
1857 buf += "1) { id _tmp = _caught;";
1858 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
1859 } else if (catchDecl) {
1860 QualType t = catchDecl->getType();
1861 if (t == Context->getObjCIdType()) {
1862 buf += "1) { ";
1863 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1864 } else if (const ObjCObjectPointerType *Ptr =
1865 t->getAs<ObjCObjectPointerType>()) {
1866 // Should be a pointer to a class.
1867 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1868 if (IDecl) {
1869 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
1870 buf += IDecl->getNameAsString();
1871 buf += "\"), (struct objc_object *)_caught)) { ";
1872 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1873 }
1874 }
1875 // Now rewrite the body...
1876 lastCatchBody = Catch->getCatchBody();
1877 SourceLocation rParenLoc = Catch->getRParenLoc();
1878 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1879 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1880 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1881 assert((*rParenBuf == ')') && "bogus @catch paren location");
1882 assert((*bodyBuf == '{') && "bogus @catch body location");
1883
1884 // Here we replace ") {" with "= _caught;" (which initializes and
1885 // declares the @catch parameter).
1886 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
1887 } else {
1888 llvm_unreachable("@catch rewrite bug");
1889 }
1890 }
1891 // Complete the catch list...
1892 if (lastCatchBody) {
1893 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1894 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1895 "bogus @catch body location");
1896
1897 // Insert the last (implicit) else clause *before* the right curly brace.
1898 bodyLoc = bodyLoc.getLocWithOffset(-1);
1899 buf = "} /* last catch end */\n";
1900 buf += "else {\n";
1901 buf += " _rethrow = _caught;\n";
1902 buf += " objc_exception_try_exit(&_stack);\n";
1903 buf += "} } /* @catch end */\n";
1904 if (!S->getFinallyStmt())
1905 buf += "}\n";
1906 InsertText(bodyLoc, buf);
1907
1908 // Set lastCurlyLoc
1909 lastCurlyLoc = lastCatchBody->getLocEnd();
1910 }
1911 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
1912 startLoc = finalStmt->getLocStart();
1913 startBuf = SM->getCharacterData(startLoc);
1914 assert((*startBuf == '@') && "bogus @finally start");
1915
1916 ReplaceText(startLoc, 8, "/* @finally */");
1917
1918 Stmt *body = finalStmt->getFinallyBody();
1919 SourceLocation startLoc = body->getLocStart();
1920 SourceLocation endLoc = body->getLocEnd();
1921 assert(*SM->getCharacterData(startLoc) == '{' &&
1922 "bogus @finally body location");
1923 assert(*SM->getCharacterData(endLoc) == '}' &&
1924 "bogus @finally body location");
1925
1926 startLoc = startLoc.getLocWithOffset(1);
1927 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
1928 endLoc = endLoc.getLocWithOffset(-1);
1929 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
1930
1931 // Set lastCurlyLoc
1932 lastCurlyLoc = body->getLocEnd();
1933
1934 // Now check for any return/continue/go statements within the @try.
1935 WarnAboutReturnGotoStmts(S->getTryBody());
1936 } else { /* no finally clause - make sure we synthesize an implicit one */
1937 buf = "{ /* implicit finally clause */\n";
1938 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1939 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1940 buf += "}";
1941 ReplaceText(lastCurlyLoc, 1, buf);
1942
1943 // Now check for any return/continue/go statements within the @try.
1944 // The implicit finally clause won't called if the @try contains any
1945 // jump statements.
1946 bool hasReturns = false;
1947 HasReturnStmts(S->getTryBody(), hasReturns);
1948 if (hasReturns)
1949 RewriteTryReturnStmts(S->getTryBody());
1950 }
1951 // Now emit the final closing curly brace...
1952 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
1953 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
1954 return 0;
1955}
1956
1957// This can't be done with ReplaceStmt(S, ThrowExpr), since
1958// the throw expression is typically a message expression that's already
1959// been rewritten! (which implies the SourceLocation's are invalid).
1960Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1961 // Get the start location and compute the semi location.
1962 SourceLocation startLoc = S->getLocStart();
1963 const char *startBuf = SM->getCharacterData(startLoc);
1964
1965 assert((*startBuf == '@') && "bogus @throw location");
1966
1967 std::string buf;
1968 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1969 if (S->getThrowExpr())
1970 buf = "objc_exception_throw(";
1971 else // add an implicit argument
1972 buf = "objc_exception_throw(_caught";
1973
1974 // handle "@ throw" correctly.
1975 const char *wBuf = strchr(startBuf, 'w');
1976 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1977 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1978
1979 const char *semiBuf = strchr(startBuf, ';');
1980 assert((*semiBuf == ';') && "@throw: can't find ';'");
1981 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
1982 ReplaceText(semiLoc, 1, ");");
1983 return 0;
1984}
1985
1986Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1987 // Create a new string expression.
1988 QualType StrType = Context->getPointerType(Context->CharTy);
1989 std::string StrEncoding;
1990 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1991 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1992 StringLiteral::Ascii, false,
1993 StrType, SourceLocation());
1994 ReplaceStmt(Exp, Replacement);
1995
1996 // Replace this subexpr in the parent.
1997 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1998 return Replacement;
1999}
2000
2001Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2002 if (!SelGetUidFunctionDecl)
2003 SynthSelGetUidFunctionDecl();
2004 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2005 // Create a call to sel_registerName("selName").
2006 SmallVector<Expr*, 8> SelExprs;
2007 QualType argType = Context->getPointerType(Context->CharTy);
2008 SelExprs.push_back(StringLiteral::Create(*Context,
2009 Exp->getSelector().getAsString(),
2010 StringLiteral::Ascii, false,
2011 argType, SourceLocation()));
2012 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2013 &SelExprs[0], SelExprs.size());
2014 ReplaceStmt(Exp, SelExp);
2015 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2016 return SelExp;
2017}
2018
2019CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2020 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2021 SourceLocation EndLoc) {
2022 // Get the type, we will need to reference it in a couple spots.
2023 QualType msgSendType = FD->getType();
2024
2025 // Create a reference to the objc_msgSend() declaration.
2026 DeclRefExpr *DRE =
2027 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
2028
2029 // Now, we cast the reference to a pointer to the objc_msgSend type.
2030 QualType pToFunc = Context->getPointerType(msgSendType);
2031 ImplicitCastExpr *ICE =
2032 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2033 DRE, 0, VK_RValue);
2034
2035 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2036
2037 CallExpr *Exp =
2038 new (Context) CallExpr(*Context, ICE, args, nargs,
2039 FT->getCallResultType(*Context),
2040 VK_RValue, EndLoc);
2041 return Exp;
2042}
2043
2044static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2045 const char *&startRef, const char *&endRef) {
2046 while (startBuf < endBuf) {
2047 if (*startBuf == '<')
2048 startRef = startBuf; // mark the start.
2049 if (*startBuf == '>') {
2050 if (startRef && *startRef == '<') {
2051 endRef = startBuf; // mark the end.
2052 return true;
2053 }
2054 return false;
2055 }
2056 startBuf++;
2057 }
2058 return false;
2059}
2060
2061static void scanToNextArgument(const char *&argRef) {
2062 int angle = 0;
2063 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2064 if (*argRef == '<')
2065 angle++;
2066 else if (*argRef == '>')
2067 angle--;
2068 argRef++;
2069 }
2070 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2071}
2072
2073bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2074 if (T->isObjCQualifiedIdType())
2075 return true;
2076 if (const PointerType *PT = T->getAs<PointerType>()) {
2077 if (PT->getPointeeType()->isObjCQualifiedIdType())
2078 return true;
2079 }
2080 if (T->isObjCObjectPointerType()) {
2081 T = T->getPointeeType();
2082 return T->isObjCQualifiedInterfaceType();
2083 }
2084 if (T->isArrayType()) {
2085 QualType ElemTy = Context->getBaseElementType(T);
2086 return needToScanForQualifiers(ElemTy);
2087 }
2088 return false;
2089}
2090
2091void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2092 QualType Type = E->getType();
2093 if (needToScanForQualifiers(Type)) {
2094 SourceLocation Loc, EndLoc;
2095
2096 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2097 Loc = ECE->getLParenLoc();
2098 EndLoc = ECE->getRParenLoc();
2099 } else {
2100 Loc = E->getLocStart();
2101 EndLoc = E->getLocEnd();
2102 }
2103 // This will defend against trying to rewrite synthesized expressions.
2104 if (Loc.isInvalid() || EndLoc.isInvalid())
2105 return;
2106
2107 const char *startBuf = SM->getCharacterData(Loc);
2108 const char *endBuf = SM->getCharacterData(EndLoc);
2109 const char *startRef = 0, *endRef = 0;
2110 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2111 // Get the locations of the startRef, endRef.
2112 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2113 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2114 // Comment out the protocol references.
2115 InsertText(LessLoc, "/*");
2116 InsertText(GreaterLoc, "*/");
2117 }
2118 }
2119}
2120
2121void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2122 SourceLocation Loc;
2123 QualType Type;
2124 const FunctionProtoType *proto = 0;
2125 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2126 Loc = VD->getLocation();
2127 Type = VD->getType();
2128 }
2129 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2130 Loc = FD->getLocation();
2131 // Check for ObjC 'id' and class types that have been adorned with protocol
2132 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2133 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2134 assert(funcType && "missing function type");
2135 proto = dyn_cast<FunctionProtoType>(funcType);
2136 if (!proto)
2137 return;
2138 Type = proto->getResultType();
2139 }
2140 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2141 Loc = FD->getLocation();
2142 Type = FD->getType();
2143 }
2144 else
2145 return;
2146
2147 if (needToScanForQualifiers(Type)) {
2148 // Since types are unique, we need to scan the buffer.
2149
2150 const char *endBuf = SM->getCharacterData(Loc);
2151 const char *startBuf = endBuf;
2152 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2153 startBuf--; // scan backward (from the decl location) for return type.
2154 const char *startRef = 0, *endRef = 0;
2155 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2156 // Get the locations of the startRef, endRef.
2157 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2158 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2159 // Comment out the protocol references.
2160 InsertText(LessLoc, "/*");
2161 InsertText(GreaterLoc, "*/");
2162 }
2163 }
2164 if (!proto)
2165 return; // most likely, was a variable
2166 // Now check arguments.
2167 const char *startBuf = SM->getCharacterData(Loc);
2168 const char *startFuncBuf = startBuf;
2169 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2170 if (needToScanForQualifiers(proto->getArgType(i))) {
2171 // Since types are unique, we need to scan the buffer.
2172
2173 const char *endBuf = startBuf;
2174 // scan forward (from the decl location) for argument types.
2175 scanToNextArgument(endBuf);
2176 const char *startRef = 0, *endRef = 0;
2177 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2178 // Get the locations of the startRef, endRef.
2179 SourceLocation LessLoc =
2180 Loc.getLocWithOffset(startRef-startFuncBuf);
2181 SourceLocation GreaterLoc =
2182 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2183 // Comment out the protocol references.
2184 InsertText(LessLoc, "/*");
2185 InsertText(GreaterLoc, "*/");
2186 }
2187 startBuf = ++endBuf;
2188 }
2189 else {
2190 // If the function name is derived from a macro expansion, then the
2191 // argument buffer will not follow the name. Need to speak with Chris.
2192 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2193 startBuf++; // scan forward (from the decl location) for argument types.
2194 startBuf++;
2195 }
2196 }
2197}
2198
2199void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2200 QualType QT = ND->getType();
2201 const Type* TypePtr = QT->getAs<Type>();
2202 if (!isa<TypeOfExprType>(TypePtr))
2203 return;
2204 while (isa<TypeOfExprType>(TypePtr)) {
2205 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2206 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2207 TypePtr = QT->getAs<Type>();
2208 }
2209 // FIXME. This will not work for multiple declarators; as in:
2210 // __typeof__(a) b,c,d;
2211 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2212 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2213 const char *startBuf = SM->getCharacterData(DeclLoc);
2214 if (ND->getInit()) {
2215 std::string Name(ND->getNameAsString());
2216 TypeAsString += " " + Name + " = ";
2217 Expr *E = ND->getInit();
2218 SourceLocation startLoc;
2219 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2220 startLoc = ECE->getLParenLoc();
2221 else
2222 startLoc = E->getLocStart();
2223 startLoc = SM->getExpansionLoc(startLoc);
2224 const char *endBuf = SM->getCharacterData(startLoc);
2225 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2226 }
2227 else {
2228 SourceLocation X = ND->getLocEnd();
2229 X = SM->getExpansionLoc(X);
2230 const char *endBuf = SM->getCharacterData(X);
2231 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2232 }
2233}
2234
2235// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2236void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2237 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2238 SmallVector<QualType, 16> ArgTys;
2239 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2240 QualType getFuncType =
2241 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2242 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2243 SourceLocation(),
2244 SourceLocation(),
2245 SelGetUidIdent, getFuncType, 0,
2246 SC_Extern,
2247 SC_None, false);
2248}
2249
2250void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2251 // declared in <objc/objc.h>
2252 if (FD->getIdentifier() &&
2253 FD->getName() == "sel_registerName") {
2254 SelGetUidFunctionDecl = FD;
2255 return;
2256 }
2257 RewriteObjCQualifiedInterfaceTypes(FD);
2258}
2259
2260void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2261 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2262 const char *argPtr = TypeString.c_str();
2263 if (!strchr(argPtr, '^')) {
2264 Str += TypeString;
2265 return;
2266 }
2267 while (*argPtr) {
2268 Str += (*argPtr == '^' ? '*' : *argPtr);
2269 argPtr++;
2270 }
2271}
2272
2273// FIXME. Consolidate this routine with RewriteBlockPointerType.
2274void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2275 ValueDecl *VD) {
2276 QualType Type = VD->getType();
2277 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2278 const char *argPtr = TypeString.c_str();
2279 int paren = 0;
2280 while (*argPtr) {
2281 switch (*argPtr) {
2282 case '(':
2283 Str += *argPtr;
2284 paren++;
2285 break;
2286 case ')':
2287 Str += *argPtr;
2288 paren--;
2289 break;
2290 case '^':
2291 Str += '*';
2292 if (paren == 1)
2293 Str += VD->getNameAsString();
2294 break;
2295 default:
2296 Str += *argPtr;
2297 break;
2298 }
2299 argPtr++;
2300 }
2301}
2302
2303
2304void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2305 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2306 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2307 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2308 if (!proto)
2309 return;
2310 QualType Type = proto->getResultType();
2311 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2312 FdStr += " ";
2313 FdStr += FD->getName();
2314 FdStr += "(";
2315 unsigned numArgs = proto->getNumArgs();
2316 for (unsigned i = 0; i < numArgs; i++) {
2317 QualType ArgType = proto->getArgType(i);
2318 RewriteBlockPointerType(FdStr, ArgType);
2319 if (i+1 < numArgs)
2320 FdStr += ", ";
2321 }
2322 FdStr += ");\n";
2323 InsertText(FunLocStart, FdStr);
2324 CurFunctionDeclToDeclareForBlock = 0;
2325}
2326
2327// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2328void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2329 if (SuperContructorFunctionDecl)
2330 return;
2331 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2332 SmallVector<QualType, 16> ArgTys;
2333 QualType argT = Context->getObjCIdType();
2334 assert(!argT.isNull() && "Can't find 'id' type");
2335 ArgTys.push_back(argT);
2336 ArgTys.push_back(argT);
2337 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2338 &ArgTys[0], ArgTys.size());
2339 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2340 SourceLocation(),
2341 SourceLocation(),
2342 msgSendIdent, msgSendType, 0,
2343 SC_Extern,
2344 SC_None, false);
2345}
2346
2347// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2348void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2349 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2350 SmallVector<QualType, 16> ArgTys;
2351 QualType argT = Context->getObjCIdType();
2352 assert(!argT.isNull() && "Can't find 'id' type");
2353 ArgTys.push_back(argT);
2354 argT = Context->getObjCSelType();
2355 assert(!argT.isNull() && "Can't find 'SEL' type");
2356 ArgTys.push_back(argT);
2357 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2358 &ArgTys[0], ArgTys.size(),
2359 true /*isVariadic*/);
2360 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2361 SourceLocation(),
2362 SourceLocation(),
2363 msgSendIdent, msgSendType, 0,
2364 SC_Extern,
2365 SC_None, false);
2366}
2367
2368// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2369void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2370 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2371 SmallVector<QualType, 16> ArgTys;
2372 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2373 SourceLocation(), SourceLocation(),
2374 &Context->Idents.get("objc_super"));
2375 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2376 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2377 ArgTys.push_back(argT);
2378 argT = Context->getObjCSelType();
2379 assert(!argT.isNull() && "Can't find 'SEL' type");
2380 ArgTys.push_back(argT);
2381 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2382 &ArgTys[0], ArgTys.size(),
2383 true /*isVariadic*/);
2384 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2385 SourceLocation(),
2386 SourceLocation(),
2387 msgSendIdent, msgSendType, 0,
2388 SC_Extern,
2389 SC_None, false);
2390}
2391
2392// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2393void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2394 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2395 SmallVector<QualType, 16> ArgTys;
2396 QualType argT = Context->getObjCIdType();
2397 assert(!argT.isNull() && "Can't find 'id' type");
2398 ArgTys.push_back(argT);
2399 argT = Context->getObjCSelType();
2400 assert(!argT.isNull() && "Can't find 'SEL' type");
2401 ArgTys.push_back(argT);
2402 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2403 &ArgTys[0], ArgTys.size(),
2404 true /*isVariadic*/);
2405 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2406 SourceLocation(),
2407 SourceLocation(),
2408 msgSendIdent, msgSendType, 0,
2409 SC_Extern,
2410 SC_None, false);
2411}
2412
2413// SynthMsgSendSuperStretFunctionDecl -
2414// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2415void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2416 IdentifierInfo *msgSendIdent =
2417 &Context->Idents.get("objc_msgSendSuper_stret");
2418 SmallVector<QualType, 16> ArgTys;
2419 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2420 SourceLocation(), SourceLocation(),
2421 &Context->Idents.get("objc_super"));
2422 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2423 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2424 ArgTys.push_back(argT);
2425 argT = Context->getObjCSelType();
2426 assert(!argT.isNull() && "Can't find 'SEL' type");
2427 ArgTys.push_back(argT);
2428 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2429 &ArgTys[0], ArgTys.size(),
2430 true /*isVariadic*/);
2431 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2432 SourceLocation(),
2433 SourceLocation(),
2434 msgSendIdent, msgSendType, 0,
2435 SC_Extern,
2436 SC_None, false);
2437}
2438
2439// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2440void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2441 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2442 SmallVector<QualType, 16> ArgTys;
2443 QualType argT = Context->getObjCIdType();
2444 assert(!argT.isNull() && "Can't find 'id' type");
2445 ArgTys.push_back(argT);
2446 argT = Context->getObjCSelType();
2447 assert(!argT.isNull() && "Can't find 'SEL' type");
2448 ArgTys.push_back(argT);
2449 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2450 &ArgTys[0], ArgTys.size(),
2451 true /*isVariadic*/);
2452 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2453 SourceLocation(),
2454 SourceLocation(),
2455 msgSendIdent, msgSendType, 0,
2456 SC_Extern,
2457 SC_None, false);
2458}
2459
2460// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2461void RewriteModernObjC::SynthGetClassFunctionDecl() {
2462 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2463 SmallVector<QualType, 16> ArgTys;
2464 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2465 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2466 &ArgTys[0], ArgTys.size());
2467 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2468 SourceLocation(),
2469 SourceLocation(),
2470 getClassIdent, getClassType, 0,
2471 SC_Extern,
2472 SC_None, false);
2473}
2474
2475// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2476void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2477 IdentifierInfo *getSuperClassIdent =
2478 &Context->Idents.get("class_getSuperclass");
2479 SmallVector<QualType, 16> ArgTys;
2480 ArgTys.push_back(Context->getObjCClassType());
2481 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2482 &ArgTys[0], ArgTys.size());
2483 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2484 SourceLocation(),
2485 SourceLocation(),
2486 getSuperClassIdent,
2487 getClassType, 0,
2488 SC_Extern,
2489 SC_None,
2490 false);
2491}
2492
2493// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2494void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2495 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2496 SmallVector<QualType, 16> ArgTys;
2497 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2498 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2499 &ArgTys[0], ArgTys.size());
2500 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2501 SourceLocation(),
2502 SourceLocation(),
2503 getClassIdent, getClassType, 0,
2504 SC_Extern,
2505 SC_None, false);
2506}
2507
2508Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2509 QualType strType = getConstantStringStructType();
2510
2511 std::string S = "__NSConstantStringImpl_";
2512
2513 std::string tmpName = InFileName;
2514 unsigned i;
2515 for (i=0; i < tmpName.length(); i++) {
2516 char c = tmpName.at(i);
2517 // replace any non alphanumeric characters with '_'.
2518 if (!isalpha(c) && (c < '0' || c > '9'))
2519 tmpName[i] = '_';
2520 }
2521 S += tmpName;
2522 S += "_";
2523 S += utostr(NumObjCStringLiterals++);
2524
2525 Preamble += "static __NSConstantStringImpl " + S;
2526 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2527 Preamble += "0x000007c8,"; // utf8_str
2528 // The pretty printer for StringLiteral handles escape characters properly.
2529 std::string prettyBufS;
2530 llvm::raw_string_ostream prettyBuf(prettyBufS);
2531 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2532 PrintingPolicy(LangOpts));
2533 Preamble += prettyBuf.str();
2534 Preamble += ",";
2535 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2536
2537 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2538 SourceLocation(), &Context->Idents.get(S),
2539 strType, 0, SC_Static, SC_None);
2540 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2541 SourceLocation());
2542 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2543 Context->getPointerType(DRE->getType()),
2544 VK_RValue, OK_Ordinary,
2545 SourceLocation());
2546 // cast to NSConstantString *
2547 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2548 CK_CPointerToObjCPointerCast, Unop);
2549 ReplaceStmt(Exp, cast);
2550 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2551 return cast;
2552}
2553
2554// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2555QualType RewriteModernObjC::getSuperStructType() {
2556 if (!SuperStructDecl) {
2557 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2558 SourceLocation(), SourceLocation(),
2559 &Context->Idents.get("objc_super"));
2560 QualType FieldTypes[2];
2561
2562 // struct objc_object *receiver;
2563 FieldTypes[0] = Context->getObjCIdType();
2564 // struct objc_class *super;
2565 FieldTypes[1] = Context->getObjCClassType();
2566
2567 // Create fields
2568 for (unsigned i = 0; i < 2; ++i) {
2569 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2570 SourceLocation(),
2571 SourceLocation(), 0,
2572 FieldTypes[i], 0,
2573 /*BitWidth=*/0,
2574 /*Mutable=*/false,
2575 /*HasInit=*/false));
2576 }
2577
2578 SuperStructDecl->completeDefinition();
2579 }
2580 return Context->getTagDeclType(SuperStructDecl);
2581}
2582
2583QualType RewriteModernObjC::getConstantStringStructType() {
2584 if (!ConstantStringDecl) {
2585 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2586 SourceLocation(), SourceLocation(),
2587 &Context->Idents.get("__NSConstantStringImpl"));
2588 QualType FieldTypes[4];
2589
2590 // struct objc_object *receiver;
2591 FieldTypes[0] = Context->getObjCIdType();
2592 // int flags;
2593 FieldTypes[1] = Context->IntTy;
2594 // char *str;
2595 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2596 // long length;
2597 FieldTypes[3] = Context->LongTy;
2598
2599 // Create fields
2600 for (unsigned i = 0; i < 4; ++i) {
2601 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2602 ConstantStringDecl,
2603 SourceLocation(),
2604 SourceLocation(), 0,
2605 FieldTypes[i], 0,
2606 /*BitWidth=*/0,
2607 /*Mutable=*/true,
2608 /*HasInit=*/false));
2609 }
2610
2611 ConstantStringDecl->completeDefinition();
2612 }
2613 return Context->getTagDeclType(ConstantStringDecl);
2614}
2615
2616Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2617 SourceLocation StartLoc,
2618 SourceLocation EndLoc) {
2619 if (!SelGetUidFunctionDecl)
2620 SynthSelGetUidFunctionDecl();
2621 if (!MsgSendFunctionDecl)
2622 SynthMsgSendFunctionDecl();
2623 if (!MsgSendSuperFunctionDecl)
2624 SynthMsgSendSuperFunctionDecl();
2625 if (!MsgSendStretFunctionDecl)
2626 SynthMsgSendStretFunctionDecl();
2627 if (!MsgSendSuperStretFunctionDecl)
2628 SynthMsgSendSuperStretFunctionDecl();
2629 if (!MsgSendFpretFunctionDecl)
2630 SynthMsgSendFpretFunctionDecl();
2631 if (!GetClassFunctionDecl)
2632 SynthGetClassFunctionDecl();
2633 if (!GetSuperClassFunctionDecl)
2634 SynthGetSuperClassFunctionDecl();
2635 if (!GetMetaClassFunctionDecl)
2636 SynthGetMetaClassFunctionDecl();
2637
2638 // default to objc_msgSend().
2639 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2640 // May need to use objc_msgSend_stret() as well.
2641 FunctionDecl *MsgSendStretFlavor = 0;
2642 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2643 QualType resultType = mDecl->getResultType();
2644 if (resultType->isRecordType())
2645 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2646 else if (resultType->isRealFloatingType())
2647 MsgSendFlavor = MsgSendFpretFunctionDecl;
2648 }
2649
2650 // Synthesize a call to objc_msgSend().
2651 SmallVector<Expr*, 8> MsgExprs;
2652 switch (Exp->getReceiverKind()) {
2653 case ObjCMessageExpr::SuperClass: {
2654 MsgSendFlavor = MsgSendSuperFunctionDecl;
2655 if (MsgSendStretFlavor)
2656 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2657 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2658
2659 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2660
2661 SmallVector<Expr*, 4> InitExprs;
2662
2663 // set the receiver to self, the first argument to all methods.
2664 InitExprs.push_back(
2665 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2666 CK_BitCast,
2667 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2668 Context->getObjCIdType(),
2669 VK_RValue,
2670 SourceLocation()))
2671 ); // set the 'receiver'.
2672
2673 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2674 SmallVector<Expr*, 8> ClsExprs;
2675 QualType argType = Context->getPointerType(Context->CharTy);
2676 ClsExprs.push_back(StringLiteral::Create(*Context,
2677 ClassDecl->getIdentifier()->getName(),
2678 StringLiteral::Ascii, false,
2679 argType, SourceLocation()));
2680 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2681 &ClsExprs[0],
2682 ClsExprs.size(),
2683 StartLoc,
2684 EndLoc);
2685 // (Class)objc_getClass("CurrentClass")
2686 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2687 Context->getObjCClassType(),
2688 CK_BitCast, Cls);
2689 ClsExprs.clear();
2690 ClsExprs.push_back(ArgExpr);
2691 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2692 &ClsExprs[0], ClsExprs.size(),
2693 StartLoc, EndLoc);
2694
2695 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2696 // To turn off a warning, type-cast to 'id'
2697 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2698 NoTypeInfoCStyleCastExpr(Context,
2699 Context->getObjCIdType(),
2700 CK_BitCast, Cls));
2701 // struct objc_super
2702 QualType superType = getSuperStructType();
2703 Expr *SuperRep;
2704
2705 if (LangOpts.MicrosoftExt) {
2706 SynthSuperContructorFunctionDecl();
2707 // Simulate a contructor call...
2708 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2709 superType, VK_LValue,
2710 SourceLocation());
2711 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2712 InitExprs.size(),
2713 superType, VK_LValue,
2714 SourceLocation());
2715 // The code for super is a little tricky to prevent collision with
2716 // the structure definition in the header. The rewriter has it's own
2717 // internal definition (__rw_objc_super) that is uses. This is why
2718 // we need the cast below. For example:
2719 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2720 //
2721 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2722 Context->getPointerType(SuperRep->getType()),
2723 VK_RValue, OK_Ordinary,
2724 SourceLocation());
2725 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2726 Context->getPointerType(superType),
2727 CK_BitCast, SuperRep);
2728 } else {
2729 // (struct objc_super) { <exprs from above> }
2730 InitListExpr *ILE =
2731 new (Context) InitListExpr(*Context, SourceLocation(),
2732 &InitExprs[0], InitExprs.size(),
2733 SourceLocation());
2734 TypeSourceInfo *superTInfo
2735 = Context->getTrivialTypeSourceInfo(superType);
2736 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2737 superType, VK_LValue,
2738 ILE, false);
2739 // struct objc_super *
2740 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2741 Context->getPointerType(SuperRep->getType()),
2742 VK_RValue, OK_Ordinary,
2743 SourceLocation());
2744 }
2745 MsgExprs.push_back(SuperRep);
2746 break;
2747 }
2748
2749 case ObjCMessageExpr::Class: {
2750 SmallVector<Expr*, 8> ClsExprs;
2751 QualType argType = Context->getPointerType(Context->CharTy);
2752 ObjCInterfaceDecl *Class
2753 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2754 IdentifierInfo *clsName = Class->getIdentifier();
2755 ClsExprs.push_back(StringLiteral::Create(*Context,
2756 clsName->getName(),
2757 StringLiteral::Ascii, false,
2758 argType, SourceLocation()));
2759 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2760 &ClsExprs[0],
2761 ClsExprs.size(),
2762 StartLoc, EndLoc);
2763 MsgExprs.push_back(Cls);
2764 break;
2765 }
2766
2767 case ObjCMessageExpr::SuperInstance:{
2768 MsgSendFlavor = MsgSendSuperFunctionDecl;
2769 if (MsgSendStretFlavor)
2770 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2771 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2772 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2773 SmallVector<Expr*, 4> InitExprs;
2774
2775 InitExprs.push_back(
2776 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2777 CK_BitCast,
2778 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2779 Context->getObjCIdType(),
2780 VK_RValue, SourceLocation()))
2781 ); // set the 'receiver'.
2782
2783 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2784 SmallVector<Expr*, 8> ClsExprs;
2785 QualType argType = Context->getPointerType(Context->CharTy);
2786 ClsExprs.push_back(StringLiteral::Create(*Context,
2787 ClassDecl->getIdentifier()->getName(),
2788 StringLiteral::Ascii, false, argType,
2789 SourceLocation()));
2790 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2791 &ClsExprs[0],
2792 ClsExprs.size(),
2793 StartLoc, EndLoc);
2794 // (Class)objc_getClass("CurrentClass")
2795 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2796 Context->getObjCClassType(),
2797 CK_BitCast, Cls);
2798 ClsExprs.clear();
2799 ClsExprs.push_back(ArgExpr);
2800 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2801 &ClsExprs[0], ClsExprs.size(),
2802 StartLoc, EndLoc);
2803
2804 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2805 // To turn off a warning, type-cast to 'id'
2806 InitExprs.push_back(
2807 // set 'super class', using class_getSuperclass().
2808 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2809 CK_BitCast, Cls));
2810 // struct objc_super
2811 QualType superType = getSuperStructType();
2812 Expr *SuperRep;
2813
2814 if (LangOpts.MicrosoftExt) {
2815 SynthSuperContructorFunctionDecl();
2816 // Simulate a contructor call...
2817 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2818 superType, VK_LValue,
2819 SourceLocation());
2820 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2821 InitExprs.size(),
2822 superType, VK_LValue, SourceLocation());
2823 // The code for super is a little tricky to prevent collision with
2824 // the structure definition in the header. The rewriter has it's own
2825 // internal definition (__rw_objc_super) that is uses. This is why
2826 // we need the cast below. For example:
2827 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2828 //
2829 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2830 Context->getPointerType(SuperRep->getType()),
2831 VK_RValue, OK_Ordinary,
2832 SourceLocation());
2833 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2834 Context->getPointerType(superType),
2835 CK_BitCast, SuperRep);
2836 } else {
2837 // (struct objc_super) { <exprs from above> }
2838 InitListExpr *ILE =
2839 new (Context) InitListExpr(*Context, SourceLocation(),
2840 &InitExprs[0], InitExprs.size(),
2841 SourceLocation());
2842 TypeSourceInfo *superTInfo
2843 = Context->getTrivialTypeSourceInfo(superType);
2844 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2845 superType, VK_RValue, ILE,
2846 false);
2847 }
2848 MsgExprs.push_back(SuperRep);
2849 break;
2850 }
2851
2852 case ObjCMessageExpr::Instance: {
2853 // Remove all type-casts because it may contain objc-style types; e.g.
2854 // Foo<Proto> *.
2855 Expr *recExpr = Exp->getInstanceReceiver();
2856 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2857 recExpr = CE->getSubExpr();
2858 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2859 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2860 ? CK_BlockPointerToObjCPointerCast
2861 : CK_CPointerToObjCPointerCast;
2862
2863 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2864 CK, recExpr);
2865 MsgExprs.push_back(recExpr);
2866 break;
2867 }
2868 }
2869
2870 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2871 SmallVector<Expr*, 8> SelExprs;
2872 QualType argType = Context->getPointerType(Context->CharTy);
2873 SelExprs.push_back(StringLiteral::Create(*Context,
2874 Exp->getSelector().getAsString(),
2875 StringLiteral::Ascii, false,
2876 argType, SourceLocation()));
2877 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2878 &SelExprs[0], SelExprs.size(),
2879 StartLoc,
2880 EndLoc);
2881 MsgExprs.push_back(SelExp);
2882
2883 // Now push any user supplied arguments.
2884 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
2885 Expr *userExpr = Exp->getArg(i);
2886 // Make all implicit casts explicit...ICE comes in handy:-)
2887 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2888 // Reuse the ICE type, it is exactly what the doctor ordered.
2889 QualType type = ICE->getType();
2890 if (needToScanForQualifiers(type))
2891 type = Context->getObjCIdType();
2892 // Make sure we convert "type (^)(...)" to "type (*)(...)".
2893 (void)convertBlockPointerToFunctionPointer(type);
2894 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2895 CastKind CK;
2896 if (SubExpr->getType()->isIntegralType(*Context) &&
2897 type->isBooleanType()) {
2898 CK = CK_IntegralToBoolean;
2899 } else if (type->isObjCObjectPointerType()) {
2900 if (SubExpr->getType()->isBlockPointerType()) {
2901 CK = CK_BlockPointerToObjCPointerCast;
2902 } else if (SubExpr->getType()->isPointerType()) {
2903 CK = CK_CPointerToObjCPointerCast;
2904 } else {
2905 CK = CK_BitCast;
2906 }
2907 } else {
2908 CK = CK_BitCast;
2909 }
2910
2911 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2912 }
2913 // Make id<P...> cast into an 'id' cast.
2914 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2915 if (CE->getType()->isObjCQualifiedIdType()) {
2916 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2917 userExpr = CE->getSubExpr();
2918 CastKind CK;
2919 if (userExpr->getType()->isIntegralType(*Context)) {
2920 CK = CK_IntegralToPointer;
2921 } else if (userExpr->getType()->isBlockPointerType()) {
2922 CK = CK_BlockPointerToObjCPointerCast;
2923 } else if (userExpr->getType()->isPointerType()) {
2924 CK = CK_CPointerToObjCPointerCast;
2925 } else {
2926 CK = CK_BitCast;
2927 }
2928 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2929 CK, userExpr);
2930 }
2931 }
2932 MsgExprs.push_back(userExpr);
2933 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2934 // out the argument in the original expression (since we aren't deleting
2935 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
2936 //Exp->setArg(i, 0);
2937 }
2938 // Generate the funky cast.
2939 CastExpr *cast;
2940 SmallVector<QualType, 8> ArgTypes;
2941 QualType returnType;
2942
2943 // Push 'id' and 'SEL', the 2 implicit arguments.
2944 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2945 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2946 else
2947 ArgTypes.push_back(Context->getObjCIdType());
2948 ArgTypes.push_back(Context->getObjCSelType());
2949 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2950 // Push any user argument types.
2951 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2952 E = OMD->param_end(); PI != E; ++PI) {
2953 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
2954 ? Context->getObjCIdType()
2955 : (*PI)->getType();
2956 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2957 (void)convertBlockPointerToFunctionPointer(t);
2958 ArgTypes.push_back(t);
2959 }
2960 returnType = Exp->getType();
2961 convertToUnqualifiedObjCType(returnType);
2962 (void)convertBlockPointerToFunctionPointer(returnType);
2963 } else {
2964 returnType = Context->getObjCIdType();
2965 }
2966 // Get the type, we will need to reference it in a couple spots.
2967 QualType msgSendType = MsgSendFlavor->getType();
2968
2969 // Create a reference to the objc_msgSend() declaration.
2970 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
2971 VK_LValue, SourceLocation());
2972
2973 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2974 // If we don't do this cast, we get the following bizarre warning/note:
2975 // xx.m:13: warning: function called through a non-compatible type
2976 // xx.m:13: note: if this code is reached, the program will abort
2977 cast = NoTypeInfoCStyleCastExpr(Context,
2978 Context->getPointerType(Context->VoidTy),
2979 CK_BitCast, DRE);
2980
2981 // Now do the "normal" pointer to function cast.
2982 QualType castType =
2983 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2984 // If we don't have a method decl, force a variadic cast.
2985 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
2986 castType = Context->getPointerType(castType);
2987 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2988 cast);
2989
2990 // Don't forget the parens to enforce the proper binding.
2991 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2992
2993 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2994 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2995 MsgExprs.size(),
2996 FT->getResultType(), VK_RValue,
2997 EndLoc);
2998 Stmt *ReplacingStmt = CE;
2999 if (MsgSendStretFlavor) {
3000 // We have the method which returns a struct/union. Must also generate
3001 // call to objc_msgSend_stret and hang both varieties on a conditional
3002 // expression which dictate which one to envoke depending on size of
3003 // method's return type.
3004
3005 // Create a reference to the objc_msgSend_stret() declaration.
3006 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
3007 VK_LValue, SourceLocation());
3008 // Need to cast objc_msgSend_stret to "void *" (see above comment).
3009 cast = NoTypeInfoCStyleCastExpr(Context,
3010 Context->getPointerType(Context->VoidTy),
3011 CK_BitCast, STDRE);
3012 // Now do the "normal" pointer to function cast.
3013 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3014 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
3015 castType = Context->getPointerType(castType);
3016 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3017 cast);
3018
3019 // Don't forget the parens to enforce the proper binding.
3020 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3021
3022 FT = msgSendType->getAs<FunctionType>();
3023 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3024 MsgExprs.size(),
3025 FT->getResultType(), VK_RValue,
3026 SourceLocation());
3027
3028 // Build sizeof(returnType)
3029 UnaryExprOrTypeTraitExpr *sizeofExpr =
3030 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3031 Context->getTrivialTypeSourceInfo(returnType),
3032 Context->getSizeType(), SourceLocation(),
3033 SourceLocation());
3034 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3035 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3036 // For X86 it is more complicated and some kind of target specific routine
3037 // is needed to decide what to do.
3038 unsigned IntSize =
3039 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3040 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3041 llvm::APInt(IntSize, 8),
3042 Context->IntTy,
3043 SourceLocation());
3044 BinaryOperator *lessThanExpr =
3045 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3046 VK_RValue, OK_Ordinary, SourceLocation());
3047 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3048 ConditionalOperator *CondExpr =
3049 new (Context) ConditionalOperator(lessThanExpr,
3050 SourceLocation(), CE,
3051 SourceLocation(), STCE,
3052 returnType, VK_RValue, OK_Ordinary);
3053 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3054 CondExpr);
3055 }
3056 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3057 return ReplacingStmt;
3058}
3059
3060Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3061 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3062 Exp->getLocEnd());
3063
3064 // Now do the actual rewrite.
3065 ReplaceStmt(Exp, ReplacingStmt);
3066
3067 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3068 return ReplacingStmt;
3069}
3070
3071// typedef struct objc_object Protocol;
3072QualType RewriteModernObjC::getProtocolType() {
3073 if (!ProtocolTypeDecl) {
3074 TypeSourceInfo *TInfo
3075 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3076 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3077 SourceLocation(), SourceLocation(),
3078 &Context->Idents.get("Protocol"),
3079 TInfo);
3080 }
3081 return Context->getTypeDeclType(ProtocolTypeDecl);
3082}
3083
3084/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3085/// a synthesized/forward data reference (to the protocol's metadata).
3086/// The forward references (and metadata) are generated in
3087/// RewriteModernObjC::HandleTranslationUnit().
3088Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3089 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3090 IdentifierInfo *ID = &Context->Idents.get(Name);
3091 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3092 SourceLocation(), ID, getProtocolType(), 0,
3093 SC_Extern, SC_None);
3094 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3095 SourceLocation());
3096 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3097 Context->getPointerType(DRE->getType()),
3098 VK_RValue, OK_Ordinary, SourceLocation());
3099 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3100 CK_BitCast,
3101 DerefExpr);
3102 ReplaceStmt(Exp, castExpr);
3103 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3104 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3105 return castExpr;
3106
3107}
3108
3109bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3110 const char *endBuf) {
3111 while (startBuf < endBuf) {
3112 if (*startBuf == '#') {
3113 // Skip whitespace.
3114 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3115 ;
3116 if (!strncmp(startBuf, "if", strlen("if")) ||
3117 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3118 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3119 !strncmp(startBuf, "define", strlen("define")) ||
3120 !strncmp(startBuf, "undef", strlen("undef")) ||
3121 !strncmp(startBuf, "else", strlen("else")) ||
3122 !strncmp(startBuf, "elif", strlen("elif")) ||
3123 !strncmp(startBuf, "endif", strlen("endif")) ||
3124 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3125 !strncmp(startBuf, "include", strlen("include")) ||
3126 !strncmp(startBuf, "import", strlen("import")) ||
3127 !strncmp(startBuf, "include_next", strlen("include_next")))
3128 return true;
3129 }
3130 startBuf++;
3131 }
3132 return false;
3133}
3134
3135/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3136/// an objective-c class with ivars.
3137void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3138 std::string &Result) {
3139 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3140 assert(CDecl->getName() != "" &&
3141 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003142 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003143 SmallVector<ObjCIvarDecl *, 8> IVars;
3144 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3145 IVD; IVD = IVD->getNextIvar()) {
3146 // Ignore unnamed bit-fields.
3147 if (!IVD->getDeclName())
3148 continue;
3149 IVars.push_back(IVD);
3150 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003151 SourceLocation LocStart = CDecl->getLocStart();
3152 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003153
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003154 const char *startBuf = SM->getCharacterData(LocStart);
3155 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003156
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003157 // If no ivars and no root or if its root, directly or indirectly,
3158 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003159 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003160 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3161 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3162 ReplaceText(LocStart, endBuf-startBuf, Result);
3163 return;
3164 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003165
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003166 Result += "\nstruct ";
3167 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003168 Result += "_IMPL {\n";
3169
3170 if (RCDecl) {
3171 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3172 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3173 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003174 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003175
3176 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
3177 ObjCIvarDecl *IvarDecl = IVars[i];
3178 QualType Type = IvarDecl->getType();
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003179 std::string Name = IvarDecl->getNameAsString();
3180
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003181 Result += "\t";
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003182 convertObjCTypeToCStyleType(Type);
3183
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003184 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
3185 Result += Name;
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003186 if (IvarDecl->isBitField()) {
3187 Result += " : "; Result += utostr(IvarDecl->getBitWidthValue(*Context));
3188 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003189 Result += ";\n";
3190 }
3191 Result += "};\n";
3192 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3193 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003194}
3195
3196//===----------------------------------------------------------------------===//
3197// Meta Data Emission
3198//===----------------------------------------------------------------------===//
3199
3200
3201/// RewriteImplementations - This routine rewrites all method implementations
3202/// and emits meta-data.
3203
3204void RewriteModernObjC::RewriteImplementations() {
3205 int ClsDefCount = ClassImplementation.size();
3206 int CatDefCount = CategoryImplementation.size();
3207
3208 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003209 for (int i = 0; i < ClsDefCount; i++) {
3210 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3211 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3212 if (CDecl->isImplicitInterfaceDecl())
3213 assert(false &&
3214 "Legacy implicit interface rewriting not supported in moder abi");
3215 // Write struct declaration for the class matching its ivar declarations.
3216 // Note that for modern abi, this is postponed until implementation decl.
3217 // because class extensions and the implementation might declare their own
3218 // private ivars.
3219 RewriteInterfaceDecl(CDecl);
3220 RewriteImplementationDecl(OIMP);
3221 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003222
3223 for (int i = 0; i < CatDefCount; i++)
3224 RewriteImplementationDecl(CategoryImplementation[i]);
3225}
3226
3227void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3228 const std::string &Name,
3229 ValueDecl *VD, bool def) {
3230 assert(BlockByRefDeclNo.count(VD) &&
3231 "RewriteByRefString: ByRef decl missing");
3232 if (def)
3233 ResultStr += "struct ";
3234 ResultStr += "__Block_byref_" + Name +
3235 "_" + utostr(BlockByRefDeclNo[VD]) ;
3236}
3237
3238static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3239 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3240 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3241 return false;
3242}
3243
3244std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3245 StringRef funcName,
3246 std::string Tag) {
3247 const FunctionType *AFT = CE->getFunctionType();
3248 QualType RT = AFT->getResultType();
3249 std::string StructRef = "struct " + Tag;
3250 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
3251 funcName.str() + "_" + "block_func_" + utostr(i);
3252
3253 BlockDecl *BD = CE->getBlockDecl();
3254
3255 if (isa<FunctionNoProtoType>(AFT)) {
3256 // No user-supplied arguments. Still need to pass in a pointer to the
3257 // block (to reference imported block decl refs).
3258 S += "(" + StructRef + " *__cself)";
3259 } else if (BD->param_empty()) {
3260 S += "(" + StructRef + " *__cself)";
3261 } else {
3262 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3263 assert(FT && "SynthesizeBlockFunc: No function proto");
3264 S += '(';
3265 // first add the implicit argument.
3266 S += StructRef + " *__cself, ";
3267 std::string ParamStr;
3268 for (BlockDecl::param_iterator AI = BD->param_begin(),
3269 E = BD->param_end(); AI != E; ++AI) {
3270 if (AI != BD->param_begin()) S += ", ";
3271 ParamStr = (*AI)->getNameAsString();
3272 QualType QT = (*AI)->getType();
3273 if (convertBlockPointerToFunctionPointer(QT))
3274 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3275 else
3276 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3277 S += ParamStr;
3278 }
3279 if (FT->isVariadic()) {
3280 if (!BD->param_empty()) S += ", ";
3281 S += "...";
3282 }
3283 S += ')';
3284 }
3285 S += " {\n";
3286
3287 // Create local declarations to avoid rewriting all closure decl ref exprs.
3288 // First, emit a declaration for all "by ref" decls.
3289 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3290 E = BlockByRefDecls.end(); I != E; ++I) {
3291 S += " ";
3292 std::string Name = (*I)->getNameAsString();
3293 std::string TypeString;
3294 RewriteByRefString(TypeString, Name, (*I));
3295 TypeString += " *";
3296 Name = TypeString + Name;
3297 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3298 }
3299 // Next, emit a declaration for all "by copy" declarations.
3300 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3301 E = BlockByCopyDecls.end(); I != E; ++I) {
3302 S += " ";
3303 // Handle nested closure invocation. For example:
3304 //
3305 // void (^myImportedClosure)(void);
3306 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3307 //
3308 // void (^anotherClosure)(void);
3309 // anotherClosure = ^(void) {
3310 // myImportedClosure(); // import and invoke the closure
3311 // };
3312 //
3313 if (isTopLevelBlockPointerType((*I)->getType())) {
3314 RewriteBlockPointerTypeVariable(S, (*I));
3315 S += " = (";
3316 RewriteBlockPointerType(S, (*I)->getType());
3317 S += ")";
3318 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3319 }
3320 else {
3321 std::string Name = (*I)->getNameAsString();
3322 QualType QT = (*I)->getType();
3323 if (HasLocalVariableExternalStorage(*I))
3324 QT = Context->getPointerType(QT);
3325 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3326 S += Name + " = __cself->" +
3327 (*I)->getNameAsString() + "; // bound by copy\n";
3328 }
3329 }
3330 std::string RewrittenStr = RewrittenBlockExprs[CE];
3331 const char *cstr = RewrittenStr.c_str();
3332 while (*cstr++ != '{') ;
3333 S += cstr;
3334 S += "\n";
3335 return S;
3336}
3337
3338std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3339 StringRef funcName,
3340 std::string Tag) {
3341 std::string StructRef = "struct " + Tag;
3342 std::string S = "static void __";
3343
3344 S += funcName;
3345 S += "_block_copy_" + utostr(i);
3346 S += "(" + StructRef;
3347 S += "*dst, " + StructRef;
3348 S += "*src) {";
3349 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3350 E = ImportedBlockDecls.end(); I != E; ++I) {
3351 ValueDecl *VD = (*I);
3352 S += "_Block_object_assign((void*)&dst->";
3353 S += (*I)->getNameAsString();
3354 S += ", (void*)src->";
3355 S += (*I)->getNameAsString();
3356 if (BlockByRefDeclsPtrSet.count((*I)))
3357 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3358 else if (VD->getType()->isBlockPointerType())
3359 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3360 else
3361 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3362 }
3363 S += "}\n";
3364
3365 S += "\nstatic void __";
3366 S += funcName;
3367 S += "_block_dispose_" + utostr(i);
3368 S += "(" + StructRef;
3369 S += "*src) {";
3370 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3371 E = ImportedBlockDecls.end(); I != E; ++I) {
3372 ValueDecl *VD = (*I);
3373 S += "_Block_object_dispose((void*)src->";
3374 S += (*I)->getNameAsString();
3375 if (BlockByRefDeclsPtrSet.count((*I)))
3376 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3377 else if (VD->getType()->isBlockPointerType())
3378 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3379 else
3380 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3381 }
3382 S += "}\n";
3383 return S;
3384}
3385
3386std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3387 std::string Desc) {
3388 std::string S = "\nstruct " + Tag;
3389 std::string Constructor = " " + Tag;
3390
3391 S += " {\n struct __block_impl impl;\n";
3392 S += " struct " + Desc;
3393 S += "* Desc;\n";
3394
3395 Constructor += "(void *fp, "; // Invoke function pointer.
3396 Constructor += "struct " + Desc; // Descriptor pointer.
3397 Constructor += " *desc";
3398
3399 if (BlockDeclRefs.size()) {
3400 // Output all "by copy" declarations.
3401 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3402 E = BlockByCopyDecls.end(); I != E; ++I) {
3403 S += " ";
3404 std::string FieldName = (*I)->getNameAsString();
3405 std::string ArgName = "_" + FieldName;
3406 // Handle nested closure invocation. For example:
3407 //
3408 // void (^myImportedBlock)(void);
3409 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3410 //
3411 // void (^anotherBlock)(void);
3412 // anotherBlock = ^(void) {
3413 // myImportedBlock(); // import and invoke the closure
3414 // };
3415 //
3416 if (isTopLevelBlockPointerType((*I)->getType())) {
3417 S += "struct __block_impl *";
3418 Constructor += ", void *" + ArgName;
3419 } else {
3420 QualType QT = (*I)->getType();
3421 if (HasLocalVariableExternalStorage(*I))
3422 QT = Context->getPointerType(QT);
3423 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3424 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3425 Constructor += ", " + ArgName;
3426 }
3427 S += FieldName + ";\n";
3428 }
3429 // Output all "by ref" declarations.
3430 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3431 E = BlockByRefDecls.end(); I != E; ++I) {
3432 S += " ";
3433 std::string FieldName = (*I)->getNameAsString();
3434 std::string ArgName = "_" + FieldName;
3435 {
3436 std::string TypeString;
3437 RewriteByRefString(TypeString, FieldName, (*I));
3438 TypeString += " *";
3439 FieldName = TypeString + FieldName;
3440 ArgName = TypeString + ArgName;
3441 Constructor += ", " + ArgName;
3442 }
3443 S += FieldName + "; // by ref\n";
3444 }
3445 // Finish writing the constructor.
3446 Constructor += ", int flags=0)";
3447 // Initialize all "by copy" arguments.
3448 bool firsTime = true;
3449 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3450 E = BlockByCopyDecls.end(); I != E; ++I) {
3451 std::string Name = (*I)->getNameAsString();
3452 if (firsTime) {
3453 Constructor += " : ";
3454 firsTime = false;
3455 }
3456 else
3457 Constructor += ", ";
3458 if (isTopLevelBlockPointerType((*I)->getType()))
3459 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3460 else
3461 Constructor += Name + "(_" + Name + ")";
3462 }
3463 // Initialize all "by ref" arguments.
3464 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3465 E = BlockByRefDecls.end(); I != E; ++I) {
3466 std::string Name = (*I)->getNameAsString();
3467 if (firsTime) {
3468 Constructor += " : ";
3469 firsTime = false;
3470 }
3471 else
3472 Constructor += ", ";
3473 Constructor += Name + "(_" + Name + "->__forwarding)";
3474 }
3475
3476 Constructor += " {\n";
3477 if (GlobalVarDecl)
3478 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3479 else
3480 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3481 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3482
3483 Constructor += " Desc = desc;\n";
3484 } else {
3485 // Finish writing the constructor.
3486 Constructor += ", int flags=0) {\n";
3487 if (GlobalVarDecl)
3488 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3489 else
3490 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3491 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3492 Constructor += " Desc = desc;\n";
3493 }
3494 Constructor += " ";
3495 Constructor += "}\n";
3496 S += Constructor;
3497 S += "};\n";
3498 return S;
3499}
3500
3501std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3502 std::string ImplTag, int i,
3503 StringRef FunName,
3504 unsigned hasCopy) {
3505 std::string S = "\nstatic struct " + DescTag;
3506
3507 S += " {\n unsigned long reserved;\n";
3508 S += " unsigned long Block_size;\n";
3509 if (hasCopy) {
3510 S += " void (*copy)(struct ";
3511 S += ImplTag; S += "*, struct ";
3512 S += ImplTag; S += "*);\n";
3513
3514 S += " void (*dispose)(struct ";
3515 S += ImplTag; S += "*);\n";
3516 }
3517 S += "} ";
3518
3519 S += DescTag + "_DATA = { 0, sizeof(struct ";
3520 S += ImplTag + ")";
3521 if (hasCopy) {
3522 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3523 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3524 }
3525 S += "};\n";
3526 return S;
3527}
3528
3529void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3530 StringRef FunName) {
3531 // Insert declaration for the function in which block literal is used.
3532 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3533 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3534 bool RewriteSC = (GlobalVarDecl &&
3535 !Blocks.empty() &&
3536 GlobalVarDecl->getStorageClass() == SC_Static &&
3537 GlobalVarDecl->getType().getCVRQualifiers());
3538 if (RewriteSC) {
3539 std::string SC(" void __");
3540 SC += GlobalVarDecl->getNameAsString();
3541 SC += "() {}";
3542 InsertText(FunLocStart, SC);
3543 }
3544
3545 // Insert closures that were part of the function.
3546 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3547 CollectBlockDeclRefInfo(Blocks[i]);
3548 // Need to copy-in the inner copied-in variables not actually used in this
3549 // block.
3550 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
3551 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
3552 ValueDecl *VD = Exp->getDecl();
3553 BlockDeclRefs.push_back(Exp);
3554 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
3555 BlockByCopyDeclsPtrSet.insert(VD);
3556 BlockByCopyDecls.push_back(VD);
3557 }
3558 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
3559 BlockByRefDeclsPtrSet.insert(VD);
3560 BlockByRefDecls.push_back(VD);
3561 }
3562 // imported objects in the inner blocks not used in the outer
3563 // blocks must be copied/disposed in the outer block as well.
3564 if (Exp->isByRef() ||
3565 VD->getType()->isObjCObjectPointerType() ||
3566 VD->getType()->isBlockPointerType())
3567 ImportedBlockDecls.insert(VD);
3568 }
3569
3570 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3571 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3572
3573 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3574
3575 InsertText(FunLocStart, CI);
3576
3577 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3578
3579 InsertText(FunLocStart, CF);
3580
3581 if (ImportedBlockDecls.size()) {
3582 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3583 InsertText(FunLocStart, HF);
3584 }
3585 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3586 ImportedBlockDecls.size() > 0);
3587 InsertText(FunLocStart, BD);
3588
3589 BlockDeclRefs.clear();
3590 BlockByRefDecls.clear();
3591 BlockByRefDeclsPtrSet.clear();
3592 BlockByCopyDecls.clear();
3593 BlockByCopyDeclsPtrSet.clear();
3594 ImportedBlockDecls.clear();
3595 }
3596 if (RewriteSC) {
3597 // Must insert any 'const/volatile/static here. Since it has been
3598 // removed as result of rewriting of block literals.
3599 std::string SC;
3600 if (GlobalVarDecl->getStorageClass() == SC_Static)
3601 SC = "static ";
3602 if (GlobalVarDecl->getType().isConstQualified())
3603 SC += "const ";
3604 if (GlobalVarDecl->getType().isVolatileQualified())
3605 SC += "volatile ";
3606 if (GlobalVarDecl->getType().isRestrictQualified())
3607 SC += "restrict ";
3608 InsertText(FunLocStart, SC);
3609 }
3610
3611 Blocks.clear();
3612 InnerDeclRefsCount.clear();
3613 InnerDeclRefs.clear();
3614 RewrittenBlockExprs.clear();
3615}
3616
3617void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3618 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3619 StringRef FuncName = FD->getName();
3620
3621 SynthesizeBlockLiterals(FunLocStart, FuncName);
3622}
3623
3624static void BuildUniqueMethodName(std::string &Name,
3625 ObjCMethodDecl *MD) {
3626 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3627 Name = IFace->getName();
3628 Name += "__" + MD->getSelector().getAsString();
3629 // Convert colons to underscores.
3630 std::string::size_type loc = 0;
3631 while ((loc = Name.find(":", loc)) != std::string::npos)
3632 Name.replace(loc, 1, "_");
3633}
3634
3635void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3636 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3637 //SourceLocation FunLocStart = MD->getLocStart();
3638 SourceLocation FunLocStart = MD->getLocStart();
3639 std::string FuncName;
3640 BuildUniqueMethodName(FuncName, MD);
3641 SynthesizeBlockLiterals(FunLocStart, FuncName);
3642}
3643
3644void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
3645 for (Stmt::child_range CI = S->children(); CI; ++CI)
3646 if (*CI) {
3647 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3648 GetBlockDeclRefExprs(CBE->getBody());
3649 else
3650 GetBlockDeclRefExprs(*CI);
3651 }
3652 // Handle specific things.
3653 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
3654 // FIXME: Handle enums.
3655 if (!isa<FunctionDecl>(CDRE->getDecl()))
3656 BlockDeclRefs.push_back(CDRE);
3657 }
3658 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3659 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
3660 BlockDeclRefExpr *BDRE =
3661 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
3662 DRE->getType(),
3663 VK_LValue, DRE->getLocation(), false);
3664 BlockDeclRefs.push_back(BDRE);
3665 }
3666
3667 return;
3668}
3669
3670void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3671 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
3672 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
3673 for (Stmt::child_range CI = S->children(); CI; ++CI)
3674 if (*CI) {
3675 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3676 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3677 GetInnerBlockDeclRefExprs(CBE->getBody(),
3678 InnerBlockDeclRefs,
3679 InnerContexts);
3680 }
3681 else
3682 GetInnerBlockDeclRefExprs(*CI,
3683 InnerBlockDeclRefs,
3684 InnerContexts);
3685
3686 }
3687 // Handle specific things.
3688 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
3689 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
3690 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
3691 InnerBlockDeclRefs.push_back(CDRE);
3692 }
3693 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3694 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3695 if (Var->isFunctionOrMethodVarDecl())
3696 ImportedLocalExternalDecls.insert(Var);
3697 }
3698
3699 return;
3700}
3701
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003702/// convertObjCTypeToCStyleType - This routine converts such objc types
3703/// as qualified objects, and blocks to their closest c/c++ types that
3704/// it can. It returns true if input type was modified.
3705bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
3706 QualType oldT = T;
3707 convertBlockPointerToFunctionPointer(T);
3708 if (T->isFunctionPointerType()) {
3709 QualType PointeeTy;
3710 if (const PointerType* PT = T->getAs<PointerType>()) {
3711 PointeeTy = PT->getPointeeType();
3712 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
3713 T = convertFunctionTypeOfBlocks(FT);
3714 T = Context->getPointerType(T);
3715 }
3716 }
3717 }
3718
3719 convertToUnqualifiedObjCType(T);
3720 return T != oldT;
3721}
3722
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003723/// convertFunctionTypeOfBlocks - This routine converts a function type
3724/// whose result type may be a block pointer or whose argument type(s)
3725/// might be block pointers to an equivalent function type replacing
3726/// all block pointers to function pointers.
3727QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3728 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3729 // FTP will be null for closures that don't take arguments.
3730 // Generate a funky cast.
3731 SmallVector<QualType, 8> ArgTypes;
3732 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003733 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003734
3735 if (FTP) {
3736 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3737 E = FTP->arg_type_end(); I && (I != E); ++I) {
3738 QualType t = *I;
3739 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003740 if (convertObjCTypeToCStyleType(t))
3741 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003742 ArgTypes.push_back(t);
3743 }
3744 }
3745 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003746 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003747 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
3748 else FuncType = QualType(FT, 0);
3749 return FuncType;
3750}
3751
3752Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3753 // Navigate to relevant type information.
3754 const BlockPointerType *CPT = 0;
3755
3756 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3757 CPT = DRE->getType()->getAs<BlockPointerType>();
3758 } else if (const BlockDeclRefExpr *CDRE =
3759 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
3760 CPT = CDRE->getType()->getAs<BlockPointerType>();
3761 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3762 CPT = MExpr->getType()->getAs<BlockPointerType>();
3763 }
3764 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3765 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3766 }
3767 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3768 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3769 else if (const ConditionalOperator *CEXPR =
3770 dyn_cast<ConditionalOperator>(BlockExp)) {
3771 Expr *LHSExp = CEXPR->getLHS();
3772 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3773 Expr *RHSExp = CEXPR->getRHS();
3774 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3775 Expr *CONDExp = CEXPR->getCond();
3776 ConditionalOperator *CondExpr =
3777 new (Context) ConditionalOperator(CONDExp,
3778 SourceLocation(), cast<Expr>(LHSStmt),
3779 SourceLocation(), cast<Expr>(RHSStmt),
3780 Exp->getType(), VK_RValue, OK_Ordinary);
3781 return CondExpr;
3782 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3783 CPT = IRE->getType()->getAs<BlockPointerType>();
3784 } else if (const PseudoObjectExpr *POE
3785 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3786 CPT = POE->getType()->castAs<BlockPointerType>();
3787 } else {
3788 assert(1 && "RewriteBlockClass: Bad type");
3789 }
3790 assert(CPT && "RewriteBlockClass: Bad type");
3791 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3792 assert(FT && "RewriteBlockClass: Bad type");
3793 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3794 // FTP will be null for closures that don't take arguments.
3795
3796 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3797 SourceLocation(), SourceLocation(),
3798 &Context->Idents.get("__block_impl"));
3799 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3800
3801 // Generate a funky cast.
3802 SmallVector<QualType, 8> ArgTypes;
3803
3804 // Push the block argument type.
3805 ArgTypes.push_back(PtrBlock);
3806 if (FTP) {
3807 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3808 E = FTP->arg_type_end(); I && (I != E); ++I) {
3809 QualType t = *I;
3810 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3811 if (!convertBlockPointerToFunctionPointer(t))
3812 convertToUnqualifiedObjCType(t);
3813 ArgTypes.push_back(t);
3814 }
3815 }
3816 // Now do the pointer to function cast.
3817 QualType PtrToFuncCastType
3818 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
3819
3820 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3821
3822 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3823 CK_BitCast,
3824 const_cast<Expr*>(BlockExp));
3825 // Don't forget the parens to enforce the proper binding.
3826 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3827 BlkCast);
3828 //PE->dump();
3829
3830 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3831 SourceLocation(),
3832 &Context->Idents.get("FuncPtr"),
3833 Context->VoidPtrTy, 0,
3834 /*BitWidth=*/0, /*Mutable=*/true,
3835 /*HasInit=*/false);
3836 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3837 FD->getType(), VK_LValue,
3838 OK_Ordinary);
3839
3840
3841 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3842 CK_BitCast, ME);
3843 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3844
3845 SmallVector<Expr*, 8> BlkExprs;
3846 // Add the implicit argument.
3847 BlkExprs.push_back(BlkCast);
3848 // Add the user arguments.
3849 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3850 E = Exp->arg_end(); I != E; ++I) {
3851 BlkExprs.push_back(*I);
3852 }
3853 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3854 BlkExprs.size(),
3855 Exp->getType(), VK_RValue,
3856 SourceLocation());
3857 return CE;
3858}
3859
3860// We need to return the rewritten expression to handle cases where the
3861// BlockDeclRefExpr is embedded in another expression being rewritten.
3862// For example:
3863//
3864// int main() {
3865// __block Foo *f;
3866// __block int i;
3867//
3868// void (^myblock)() = ^() {
3869// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3870// i = 77;
3871// };
3872//}
3873Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
3874 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3875 // for each DeclRefExp where BYREFVAR is name of the variable.
3876 ValueDecl *VD;
3877 bool isArrow = true;
3878 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
3879 VD = BDRE->getDecl();
3880 else {
3881 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
3882 isArrow = false;
3883 }
3884
3885 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3886 SourceLocation(),
3887 &Context->Idents.get("__forwarding"),
3888 Context->VoidPtrTy, 0,
3889 /*BitWidth=*/0, /*Mutable=*/true,
3890 /*HasInit=*/false);
3891 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3892 FD, SourceLocation(),
3893 FD->getType(), VK_LValue,
3894 OK_Ordinary);
3895
3896 StringRef Name = VD->getName();
3897 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
3898 &Context->Idents.get(Name),
3899 Context->VoidPtrTy, 0,
3900 /*BitWidth=*/0, /*Mutable=*/true,
3901 /*HasInit=*/false);
3902 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
3903 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
3904
3905
3906
3907 // Need parens to enforce precedence.
3908 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3909 DeclRefExp->getExprLoc(),
3910 ME);
3911 ReplaceStmt(DeclRefExp, PE);
3912 return PE;
3913}
3914
3915// Rewrites the imported local variable V with external storage
3916// (static, extern, etc.) as *V
3917//
3918Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3919 ValueDecl *VD = DRE->getDecl();
3920 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3921 if (!ImportedLocalExternalDecls.count(Var))
3922 return DRE;
3923 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3924 VK_LValue, OK_Ordinary,
3925 DRE->getLocation());
3926 // Need parens to enforce precedence.
3927 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3928 Exp);
3929 ReplaceStmt(DRE, PE);
3930 return PE;
3931}
3932
3933void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3934 SourceLocation LocStart = CE->getLParenLoc();
3935 SourceLocation LocEnd = CE->getRParenLoc();
3936
3937 // Need to avoid trying to rewrite synthesized casts.
3938 if (LocStart.isInvalid())
3939 return;
3940 // Need to avoid trying to rewrite casts contained in macros.
3941 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3942 return;
3943
3944 const char *startBuf = SM->getCharacterData(LocStart);
3945 const char *endBuf = SM->getCharacterData(LocEnd);
3946 QualType QT = CE->getType();
3947 const Type* TypePtr = QT->getAs<Type>();
3948 if (isa<TypeOfExprType>(TypePtr)) {
3949 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3950 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3951 std::string TypeAsString = "(";
3952 RewriteBlockPointerType(TypeAsString, QT);
3953 TypeAsString += ")";
3954 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
3955 return;
3956 }
3957 // advance the location to startArgList.
3958 const char *argPtr = startBuf;
3959
3960 while (*argPtr++ && (argPtr < endBuf)) {
3961 switch (*argPtr) {
3962 case '^':
3963 // Replace the '^' with '*'.
3964 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
3965 ReplaceText(LocStart, 1, "*");
3966 break;
3967 }
3968 }
3969 return;
3970}
3971
3972void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3973 SourceLocation DeclLoc = FD->getLocation();
3974 unsigned parenCount = 0;
3975
3976 // We have 1 or more arguments that have closure pointers.
3977 const char *startBuf = SM->getCharacterData(DeclLoc);
3978 const char *startArgList = strchr(startBuf, '(');
3979
3980 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3981
3982 parenCount++;
3983 // advance the location to startArgList.
3984 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
3985 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3986
3987 const char *argPtr = startArgList;
3988
3989 while (*argPtr++ && parenCount) {
3990 switch (*argPtr) {
3991 case '^':
3992 // Replace the '^' with '*'.
3993 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
3994 ReplaceText(DeclLoc, 1, "*");
3995 break;
3996 case '(':
3997 parenCount++;
3998 break;
3999 case ')':
4000 parenCount--;
4001 break;
4002 }
4003 }
4004 return;
4005}
4006
4007bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4008 const FunctionProtoType *FTP;
4009 const PointerType *PT = QT->getAs<PointerType>();
4010 if (PT) {
4011 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4012 } else {
4013 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4014 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4015 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4016 }
4017 if (FTP) {
4018 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4019 E = FTP->arg_type_end(); I != E; ++I)
4020 if (isTopLevelBlockPointerType(*I))
4021 return true;
4022 }
4023 return false;
4024}
4025
4026bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4027 const FunctionProtoType *FTP;
4028 const PointerType *PT = QT->getAs<PointerType>();
4029 if (PT) {
4030 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4031 } else {
4032 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4033 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4034 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4035 }
4036 if (FTP) {
4037 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4038 E = FTP->arg_type_end(); I != E; ++I) {
4039 if ((*I)->isObjCQualifiedIdType())
4040 return true;
4041 if ((*I)->isObjCObjectPointerType() &&
4042 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4043 return true;
4044 }
4045
4046 }
4047 return false;
4048}
4049
4050void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4051 const char *&RParen) {
4052 const char *argPtr = strchr(Name, '(');
4053 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4054
4055 LParen = argPtr; // output the start.
4056 argPtr++; // skip past the left paren.
4057 unsigned parenCount = 1;
4058
4059 while (*argPtr && parenCount) {
4060 switch (*argPtr) {
4061 case '(': parenCount++; break;
4062 case ')': parenCount--; break;
4063 default: break;
4064 }
4065 if (parenCount) argPtr++;
4066 }
4067 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4068 RParen = argPtr; // output the end
4069}
4070
4071void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4072 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4073 RewriteBlockPointerFunctionArgs(FD);
4074 return;
4075 }
4076 // Handle Variables and Typedefs.
4077 SourceLocation DeclLoc = ND->getLocation();
4078 QualType DeclT;
4079 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4080 DeclT = VD->getType();
4081 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4082 DeclT = TDD->getUnderlyingType();
4083 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4084 DeclT = FD->getType();
4085 else
4086 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4087
4088 const char *startBuf = SM->getCharacterData(DeclLoc);
4089 const char *endBuf = startBuf;
4090 // scan backward (from the decl location) for the end of the previous decl.
4091 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4092 startBuf--;
4093 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4094 std::string buf;
4095 unsigned OrigLength=0;
4096 // *startBuf != '^' if we are dealing with a pointer to function that
4097 // may take block argument types (which will be handled below).
4098 if (*startBuf == '^') {
4099 // Replace the '^' with '*', computing a negative offset.
4100 buf = '*';
4101 startBuf++;
4102 OrigLength++;
4103 }
4104 while (*startBuf != ')') {
4105 buf += *startBuf;
4106 startBuf++;
4107 OrigLength++;
4108 }
4109 buf += ')';
4110 OrigLength++;
4111
4112 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4113 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4114 // Replace the '^' with '*' for arguments.
4115 // Replace id<P> with id/*<>*/
4116 DeclLoc = ND->getLocation();
4117 startBuf = SM->getCharacterData(DeclLoc);
4118 const char *argListBegin, *argListEnd;
4119 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4120 while (argListBegin < argListEnd) {
4121 if (*argListBegin == '^')
4122 buf += '*';
4123 else if (*argListBegin == '<') {
4124 buf += "/*";
4125 buf += *argListBegin++;
4126 OrigLength++;;
4127 while (*argListBegin != '>') {
4128 buf += *argListBegin++;
4129 OrigLength++;
4130 }
4131 buf += *argListBegin;
4132 buf += "*/";
4133 }
4134 else
4135 buf += *argListBegin;
4136 argListBegin++;
4137 OrigLength++;
4138 }
4139 buf += ')';
4140 OrigLength++;
4141 }
4142 ReplaceText(Start, OrigLength, buf);
4143
4144 return;
4145}
4146
4147
4148/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4149/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4150/// struct Block_byref_id_object *src) {
4151/// _Block_object_assign (&_dest->object, _src->object,
4152/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4153/// [|BLOCK_FIELD_IS_WEAK]) // object
4154/// _Block_object_assign(&_dest->object, _src->object,
4155/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4156/// [|BLOCK_FIELD_IS_WEAK]) // block
4157/// }
4158/// And:
4159/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4160/// _Block_object_dispose(_src->object,
4161/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4162/// [|BLOCK_FIELD_IS_WEAK]) // object
4163/// _Block_object_dispose(_src->object,
4164/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4165/// [|BLOCK_FIELD_IS_WEAK]) // block
4166/// }
4167
4168std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4169 int flag) {
4170 std::string S;
4171 if (CopyDestroyCache.count(flag))
4172 return S;
4173 CopyDestroyCache.insert(flag);
4174 S = "static void __Block_byref_id_object_copy_";
4175 S += utostr(flag);
4176 S += "(void *dst, void *src) {\n";
4177
4178 // offset into the object pointer is computed as:
4179 // void * + void* + int + int + void* + void *
4180 unsigned IntSize =
4181 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4182 unsigned VoidPtrSize =
4183 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4184
4185 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4186 S += " _Block_object_assign((char*)dst + ";
4187 S += utostr(offset);
4188 S += ", *(void * *) ((char*)src + ";
4189 S += utostr(offset);
4190 S += "), ";
4191 S += utostr(flag);
4192 S += ");\n}\n";
4193
4194 S += "static void __Block_byref_id_object_dispose_";
4195 S += utostr(flag);
4196 S += "(void *src) {\n";
4197 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4198 S += utostr(offset);
4199 S += "), ";
4200 S += utostr(flag);
4201 S += ");\n}\n";
4202 return S;
4203}
4204
4205/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4206/// the declaration into:
4207/// struct __Block_byref_ND {
4208/// void *__isa; // NULL for everything except __weak pointers
4209/// struct __Block_byref_ND *__forwarding;
4210/// int32_t __flags;
4211/// int32_t __size;
4212/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4213/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4214/// typex ND;
4215/// };
4216///
4217/// It then replaces declaration of ND variable with:
4218/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4219/// __size=sizeof(struct __Block_byref_ND),
4220/// ND=initializer-if-any};
4221///
4222///
4223void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4224 // Insert declaration for the function in which block literal is
4225 // used.
4226 if (CurFunctionDeclToDeclareForBlock)
4227 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4228 int flag = 0;
4229 int isa = 0;
4230 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4231 if (DeclLoc.isInvalid())
4232 // If type location is missing, it is because of missing type (a warning).
4233 // Use variable's location which is good for this case.
4234 DeclLoc = ND->getLocation();
4235 const char *startBuf = SM->getCharacterData(DeclLoc);
4236 SourceLocation X = ND->getLocEnd();
4237 X = SM->getExpansionLoc(X);
4238 const char *endBuf = SM->getCharacterData(X);
4239 std::string Name(ND->getNameAsString());
4240 std::string ByrefType;
4241 RewriteByRefString(ByrefType, Name, ND, true);
4242 ByrefType += " {\n";
4243 ByrefType += " void *__isa;\n";
4244 RewriteByRefString(ByrefType, Name, ND);
4245 ByrefType += " *__forwarding;\n";
4246 ByrefType += " int __flags;\n";
4247 ByrefType += " int __size;\n";
4248 // Add void *__Block_byref_id_object_copy;
4249 // void *__Block_byref_id_object_dispose; if needed.
4250 QualType Ty = ND->getType();
4251 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4252 if (HasCopyAndDispose) {
4253 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4254 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4255 }
4256
4257 QualType T = Ty;
4258 (void)convertBlockPointerToFunctionPointer(T);
4259 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4260
4261 ByrefType += " " + Name + ";\n";
4262 ByrefType += "};\n";
4263 // Insert this type in global scope. It is needed by helper function.
4264 SourceLocation FunLocStart;
4265 if (CurFunctionDef)
4266 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4267 else {
4268 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4269 FunLocStart = CurMethodDef->getLocStart();
4270 }
4271 InsertText(FunLocStart, ByrefType);
4272 if (Ty.isObjCGCWeak()) {
4273 flag |= BLOCK_FIELD_IS_WEAK;
4274 isa = 1;
4275 }
4276
4277 if (HasCopyAndDispose) {
4278 flag = BLOCK_BYREF_CALLER;
4279 QualType Ty = ND->getType();
4280 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4281 if (Ty->isBlockPointerType())
4282 flag |= BLOCK_FIELD_IS_BLOCK;
4283 else
4284 flag |= BLOCK_FIELD_IS_OBJECT;
4285 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4286 if (!HF.empty())
4287 InsertText(FunLocStart, HF);
4288 }
4289
4290 // struct __Block_byref_ND ND =
4291 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4292 // initializer-if-any};
4293 bool hasInit = (ND->getInit() != 0);
4294 unsigned flags = 0;
4295 if (HasCopyAndDispose)
4296 flags |= BLOCK_HAS_COPY_DISPOSE;
4297 Name = ND->getNameAsString();
4298 ByrefType.clear();
4299 RewriteByRefString(ByrefType, Name, ND);
4300 std::string ForwardingCastType("(");
4301 ForwardingCastType += ByrefType + " *)";
4302 if (!hasInit) {
4303 ByrefType += " " + Name + " = {(void*)";
4304 ByrefType += utostr(isa);
4305 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4306 ByrefType += utostr(flags);
4307 ByrefType += ", ";
4308 ByrefType += "sizeof(";
4309 RewriteByRefString(ByrefType, Name, ND);
4310 ByrefType += ")";
4311 if (HasCopyAndDispose) {
4312 ByrefType += ", __Block_byref_id_object_copy_";
4313 ByrefType += utostr(flag);
4314 ByrefType += ", __Block_byref_id_object_dispose_";
4315 ByrefType += utostr(flag);
4316 }
4317 ByrefType += "};\n";
4318 unsigned nameSize = Name.size();
4319 // for block or function pointer declaration. Name is aleady
4320 // part of the declaration.
4321 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4322 nameSize = 1;
4323 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4324 }
4325 else {
4326 SourceLocation startLoc;
4327 Expr *E = ND->getInit();
4328 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4329 startLoc = ECE->getLParenLoc();
4330 else
4331 startLoc = E->getLocStart();
4332 startLoc = SM->getExpansionLoc(startLoc);
4333 endBuf = SM->getCharacterData(startLoc);
4334 ByrefType += " " + Name;
4335 ByrefType += " = {(void*)";
4336 ByrefType += utostr(isa);
4337 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4338 ByrefType += utostr(flags);
4339 ByrefType += ", ";
4340 ByrefType += "sizeof(";
4341 RewriteByRefString(ByrefType, Name, ND);
4342 ByrefType += "), ";
4343 if (HasCopyAndDispose) {
4344 ByrefType += "__Block_byref_id_object_copy_";
4345 ByrefType += utostr(flag);
4346 ByrefType += ", __Block_byref_id_object_dispose_";
4347 ByrefType += utostr(flag);
4348 ByrefType += ", ";
4349 }
4350 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4351
4352 // Complete the newly synthesized compound expression by inserting a right
4353 // curly brace before the end of the declaration.
4354 // FIXME: This approach avoids rewriting the initializer expression. It
4355 // also assumes there is only one declarator. For example, the following
4356 // isn't currently supported by this routine (in general):
4357 //
4358 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4359 //
4360 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4361 const char *semiBuf = strchr(startInitializerBuf, ';');
4362 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4363 SourceLocation semiLoc =
4364 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4365
4366 InsertText(semiLoc, "}");
4367 }
4368 return;
4369}
4370
4371void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4372 // Add initializers for any closure decl refs.
4373 GetBlockDeclRefExprs(Exp->getBody());
4374 if (BlockDeclRefs.size()) {
4375 // Unique all "by copy" declarations.
4376 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4377 if (!BlockDeclRefs[i]->isByRef()) {
4378 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4379 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4380 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4381 }
4382 }
4383 // Unique all "by ref" declarations.
4384 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4385 if (BlockDeclRefs[i]->isByRef()) {
4386 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4387 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4388 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4389 }
4390 }
4391 // Find any imported blocks...they will need special attention.
4392 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4393 if (BlockDeclRefs[i]->isByRef() ||
4394 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4395 BlockDeclRefs[i]->getType()->isBlockPointerType())
4396 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4397 }
4398}
4399
4400FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4401 IdentifierInfo *ID = &Context->Idents.get(name);
4402 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4403 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4404 SourceLocation(), ID, FType, 0, SC_Extern,
4405 SC_None, false, false);
4406}
4407
4408Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
4409 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
4410 const BlockDecl *block = Exp->getBlockDecl();
4411 Blocks.push_back(Exp);
4412
4413 CollectBlockDeclRefInfo(Exp);
4414
4415 // Add inner imported variables now used in current block.
4416 int countOfInnerDecls = 0;
4417 if (!InnerBlockDeclRefs.empty()) {
4418 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
4419 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
4420 ValueDecl *VD = Exp->getDecl();
4421 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4422 // We need to save the copied-in variables in nested
4423 // blocks because it is needed at the end for some of the API generations.
4424 // See SynthesizeBlockLiterals routine.
4425 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4426 BlockDeclRefs.push_back(Exp);
4427 BlockByCopyDeclsPtrSet.insert(VD);
4428 BlockByCopyDecls.push_back(VD);
4429 }
4430 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4431 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4432 BlockDeclRefs.push_back(Exp);
4433 BlockByRefDeclsPtrSet.insert(VD);
4434 BlockByRefDecls.push_back(VD);
4435 }
4436 }
4437 // Find any imported blocks...they will need special attention.
4438 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
4439 if (InnerBlockDeclRefs[i]->isByRef() ||
4440 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4441 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4442 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4443 }
4444 InnerDeclRefsCount.push_back(countOfInnerDecls);
4445
4446 std::string FuncName;
4447
4448 if (CurFunctionDef)
4449 FuncName = CurFunctionDef->getNameAsString();
4450 else if (CurMethodDef)
4451 BuildUniqueMethodName(FuncName, CurMethodDef);
4452 else if (GlobalVarDecl)
4453 FuncName = std::string(GlobalVarDecl->getNameAsString());
4454
4455 std::string BlockNumber = utostr(Blocks.size()-1);
4456
4457 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4458 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4459
4460 // Get a pointer to the function type so we can cast appropriately.
4461 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4462 QualType FType = Context->getPointerType(BFT);
4463
4464 FunctionDecl *FD;
4465 Expr *NewRep;
4466
4467 // Simulate a contructor call...
4468 FD = SynthBlockInitFunctionDecl(Tag);
4469 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
4470 SourceLocation());
4471
4472 SmallVector<Expr*, 4> InitExprs;
4473
4474 // Initialize the block function.
4475 FD = SynthBlockInitFunctionDecl(Func);
4476 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4477 SourceLocation());
4478 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4479 CK_BitCast, Arg);
4480 InitExprs.push_back(castExpr);
4481
4482 // Initialize the block descriptor.
4483 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4484
4485 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4486 SourceLocation(), SourceLocation(),
4487 &Context->Idents.get(DescData.c_str()),
4488 Context->VoidPtrTy, 0,
4489 SC_Static, SC_None);
4490 UnaryOperator *DescRefExpr =
4491 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
4492 Context->VoidPtrTy,
4493 VK_LValue,
4494 SourceLocation()),
4495 UO_AddrOf,
4496 Context->getPointerType(Context->VoidPtrTy),
4497 VK_RValue, OK_Ordinary,
4498 SourceLocation());
4499 InitExprs.push_back(DescRefExpr);
4500
4501 // Add initializers for any closure decl refs.
4502 if (BlockDeclRefs.size()) {
4503 Expr *Exp;
4504 // Output all "by copy" declarations.
4505 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4506 E = BlockByCopyDecls.end(); I != E; ++I) {
4507 if (isObjCType((*I)->getType())) {
4508 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4509 FD = SynthBlockInitFunctionDecl((*I)->getName());
4510 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4511 SourceLocation());
4512 if (HasLocalVariableExternalStorage(*I)) {
4513 QualType QT = (*I)->getType();
4514 QT = Context->getPointerType(QT);
4515 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4516 OK_Ordinary, SourceLocation());
4517 }
4518 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4519 FD = SynthBlockInitFunctionDecl((*I)->getName());
4520 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4521 SourceLocation());
4522 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4523 CK_BitCast, Arg);
4524 } else {
4525 FD = SynthBlockInitFunctionDecl((*I)->getName());
4526 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4527 SourceLocation());
4528 if (HasLocalVariableExternalStorage(*I)) {
4529 QualType QT = (*I)->getType();
4530 QT = Context->getPointerType(QT);
4531 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4532 OK_Ordinary, SourceLocation());
4533 }
4534
4535 }
4536 InitExprs.push_back(Exp);
4537 }
4538 // Output all "by ref" declarations.
4539 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4540 E = BlockByRefDecls.end(); I != E; ++I) {
4541 ValueDecl *ND = (*I);
4542 std::string Name(ND->getNameAsString());
4543 std::string RecName;
4544 RewriteByRefString(RecName, Name, ND, true);
4545 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4546 + sizeof("struct"));
4547 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4548 SourceLocation(), SourceLocation(),
4549 II);
4550 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4551 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4552
4553 FD = SynthBlockInitFunctionDecl((*I)->getName());
4554 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4555 SourceLocation());
4556 bool isNestedCapturedVar = false;
4557 if (block)
4558 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4559 ce = block->capture_end(); ci != ce; ++ci) {
4560 const VarDecl *variable = ci->getVariable();
4561 if (variable == ND && ci->isNested()) {
4562 assert (ci->isByRef() &&
4563 "SynthBlockInitExpr - captured block variable is not byref");
4564 isNestedCapturedVar = true;
4565 break;
4566 }
4567 }
4568 // captured nested byref variable has its address passed. Do not take
4569 // its address again.
4570 if (!isNestedCapturedVar)
4571 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4572 Context->getPointerType(Exp->getType()),
4573 VK_RValue, OK_Ordinary, SourceLocation());
4574 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4575 InitExprs.push_back(Exp);
4576 }
4577 }
4578 if (ImportedBlockDecls.size()) {
4579 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4580 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4581 unsigned IntSize =
4582 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4583 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4584 Context->IntTy, SourceLocation());
4585 InitExprs.push_back(FlagExp);
4586 }
4587 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4588 FType, VK_LValue, SourceLocation());
4589 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4590 Context->getPointerType(NewRep->getType()),
4591 VK_RValue, OK_Ordinary, SourceLocation());
4592 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4593 NewRep);
4594 BlockDeclRefs.clear();
4595 BlockByRefDecls.clear();
4596 BlockByRefDeclsPtrSet.clear();
4597 BlockByCopyDecls.clear();
4598 BlockByCopyDeclsPtrSet.clear();
4599 ImportedBlockDecls.clear();
4600 return NewRep;
4601}
4602
4603bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4604 if (const ObjCForCollectionStmt * CS =
4605 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4606 return CS->getElement() == DS;
4607 return false;
4608}
4609
4610//===----------------------------------------------------------------------===//
4611// Function Body / Expression rewriting
4612//===----------------------------------------------------------------------===//
4613
4614Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4615 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4616 isa<DoStmt>(S) || isa<ForStmt>(S))
4617 Stmts.push_back(S);
4618 else if (isa<ObjCForCollectionStmt>(S)) {
4619 Stmts.push_back(S);
4620 ObjCBcLabelNo.push_back(++BcLabelCount);
4621 }
4622
4623 // Pseudo-object operations and ivar references need special
4624 // treatment because we're going to recursively rewrite them.
4625 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4626 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4627 return RewritePropertyOrImplicitSetter(PseudoOp);
4628 } else {
4629 return RewritePropertyOrImplicitGetter(PseudoOp);
4630 }
4631 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4632 return RewriteObjCIvarRefExpr(IvarRefExpr);
4633 }
4634
4635 SourceRange OrigStmtRange = S->getSourceRange();
4636
4637 // Perform a bottom up rewrite of all children.
4638 for (Stmt::child_range CI = S->children(); CI; ++CI)
4639 if (*CI) {
4640 Stmt *childStmt = (*CI);
4641 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4642 if (newStmt) {
4643 *CI = newStmt;
4644 }
4645 }
4646
4647 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4648 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
4649 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4650 InnerContexts.insert(BE->getBlockDecl());
4651 ImportedLocalExternalDecls.clear();
4652 GetInnerBlockDeclRefExprs(BE->getBody(),
4653 InnerBlockDeclRefs, InnerContexts);
4654 // Rewrite the block body in place.
4655 Stmt *SaveCurrentBody = CurrentBody;
4656 CurrentBody = BE->getBody();
4657 PropParentMap = 0;
4658 // block literal on rhs of a property-dot-sytax assignment
4659 // must be replaced by its synthesize ast so getRewrittenText
4660 // works as expected. In this case, what actually ends up on RHS
4661 // is the blockTranscribed which is the helper function for the
4662 // block literal; as in: self.c = ^() {[ace ARR];};
4663 bool saveDisableReplaceStmt = DisableReplaceStmt;
4664 DisableReplaceStmt = false;
4665 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4666 DisableReplaceStmt = saveDisableReplaceStmt;
4667 CurrentBody = SaveCurrentBody;
4668 PropParentMap = 0;
4669 ImportedLocalExternalDecls.clear();
4670 // Now we snarf the rewritten text and stash it away for later use.
4671 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4672 RewrittenBlockExprs[BE] = Str;
4673
4674 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4675
4676 //blockTranscribed->dump();
4677 ReplaceStmt(S, blockTranscribed);
4678 return blockTranscribed;
4679 }
4680 // Handle specific things.
4681 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4682 return RewriteAtEncode(AtEncode);
4683
4684 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4685 return RewriteAtSelector(AtSelector);
4686
4687 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4688 return RewriteObjCStringLiteral(AtString);
4689
4690 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4691#if 0
4692 // Before we rewrite it, put the original message expression in a comment.
4693 SourceLocation startLoc = MessExpr->getLocStart();
4694 SourceLocation endLoc = MessExpr->getLocEnd();
4695
4696 const char *startBuf = SM->getCharacterData(startLoc);
4697 const char *endBuf = SM->getCharacterData(endLoc);
4698
4699 std::string messString;
4700 messString += "// ";
4701 messString.append(startBuf, endBuf-startBuf+1);
4702 messString += "\n";
4703
4704 // FIXME: Missing definition of
4705 // InsertText(clang::SourceLocation, char const*, unsigned int).
4706 // InsertText(startLoc, messString.c_str(), messString.size());
4707 // Tried this, but it didn't work either...
4708 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4709#endif
4710 return RewriteMessageExpr(MessExpr);
4711 }
4712
4713 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4714 return RewriteObjCTryStmt(StmtTry);
4715
4716 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4717 return RewriteObjCSynchronizedStmt(StmtTry);
4718
4719 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4720 return RewriteObjCThrowStmt(StmtThrow);
4721
4722 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4723 return RewriteObjCProtocolExpr(ProtocolExp);
4724
4725 if (ObjCForCollectionStmt *StmtForCollection =
4726 dyn_cast<ObjCForCollectionStmt>(S))
4727 return RewriteObjCForCollectionStmt(StmtForCollection,
4728 OrigStmtRange.getEnd());
4729 if (BreakStmt *StmtBreakStmt =
4730 dyn_cast<BreakStmt>(S))
4731 return RewriteBreakStmt(StmtBreakStmt);
4732 if (ContinueStmt *StmtContinueStmt =
4733 dyn_cast<ContinueStmt>(S))
4734 return RewriteContinueStmt(StmtContinueStmt);
4735
4736 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4737 // and cast exprs.
4738 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4739 // FIXME: What we're doing here is modifying the type-specifier that
4740 // precedes the first Decl. In the future the DeclGroup should have
4741 // a separate type-specifier that we can rewrite.
4742 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4743 // the context of an ObjCForCollectionStmt. For example:
4744 // NSArray *someArray;
4745 // for (id <FooProtocol> index in someArray) ;
4746 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4747 // and it depends on the original text locations/positions.
4748 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4749 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4750
4751 // Blocks rewrite rules.
4752 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4753 DI != DE; ++DI) {
4754 Decl *SD = *DI;
4755 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4756 if (isTopLevelBlockPointerType(ND->getType()))
4757 RewriteBlockPointerDecl(ND);
4758 else if (ND->getType()->isFunctionPointerType())
4759 CheckFunctionPointerDecl(ND->getType(), ND);
4760 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4761 if (VD->hasAttr<BlocksAttr>()) {
4762 static unsigned uniqueByrefDeclCount = 0;
4763 assert(!BlockByRefDeclNo.count(ND) &&
4764 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4765 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4766 RewriteByRefVar(VD);
4767 }
4768 else
4769 RewriteTypeOfDecl(VD);
4770 }
4771 }
4772 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4773 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4774 RewriteBlockPointerDecl(TD);
4775 else if (TD->getUnderlyingType()->isFunctionPointerType())
4776 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4777 }
4778 }
4779 }
4780
4781 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4782 RewriteObjCQualifiedInterfaceTypes(CE);
4783
4784 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4785 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4786 assert(!Stmts.empty() && "Statement stack is empty");
4787 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4788 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4789 && "Statement stack mismatch");
4790 Stmts.pop_back();
4791 }
4792 // Handle blocks rewriting.
4793 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4794 if (BDRE->isByRef())
4795 return RewriteBlockDeclRefExpr(BDRE);
4796 }
4797 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4798 ValueDecl *VD = DRE->getDecl();
4799 if (VD->hasAttr<BlocksAttr>())
4800 return RewriteBlockDeclRefExpr(DRE);
4801 if (HasLocalVariableExternalStorage(VD))
4802 return RewriteLocalVariableExternalStorage(DRE);
4803 }
4804
4805 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4806 if (CE->getCallee()->getType()->isBlockPointerType()) {
4807 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4808 ReplaceStmt(S, BlockCall);
4809 return BlockCall;
4810 }
4811 }
4812 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4813 RewriteCastExpr(CE);
4814 }
4815#if 0
4816 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4817 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4818 ICE->getSubExpr(),
4819 SourceLocation());
4820 // Get the new text.
4821 std::string SStr;
4822 llvm::raw_string_ostream Buf(SStr);
4823 Replacement->printPretty(Buf, *Context);
4824 const std::string &Str = Buf.str();
4825
4826 printf("CAST = %s\n", &Str[0]);
4827 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4828 delete S;
4829 return Replacement;
4830 }
4831#endif
4832 // Return this stmt unmodified.
4833 return S;
4834}
4835
4836void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
4837 for (RecordDecl::field_iterator i = RD->field_begin(),
4838 e = RD->field_end(); i != e; ++i) {
4839 FieldDecl *FD = *i;
4840 if (isTopLevelBlockPointerType(FD->getType()))
4841 RewriteBlockPointerDecl(FD);
4842 if (FD->getType()->isObjCQualifiedIdType() ||
4843 FD->getType()->isObjCQualifiedInterfaceType())
4844 RewriteObjCQualifiedInterfaceTypes(FD);
4845 }
4846}
4847
4848/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4849/// main file of the input.
4850void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
4851 switch (D->getKind()) {
4852 case Decl::Function: {
4853 FunctionDecl *FD = cast<FunctionDecl>(D);
4854 if (FD->isOverloadedOperator())
4855 return;
4856
4857 // Since function prototypes don't have ParmDecl's, we check the function
4858 // prototype. This enables us to rewrite function declarations and
4859 // definitions using the same code.
4860 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4861
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00004862 if (!FD->isThisDeclarationADefinition())
4863 break;
4864
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004865 // FIXME: If this should support Obj-C++, support CXXTryStmt
4866 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4867 CurFunctionDef = FD;
4868 CurFunctionDeclToDeclareForBlock = FD;
4869 CurrentBody = Body;
4870 Body =
4871 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4872 FD->setBody(Body);
4873 CurrentBody = 0;
4874 if (PropParentMap) {
4875 delete PropParentMap;
4876 PropParentMap = 0;
4877 }
4878 // This synthesizes and inserts the block "impl" struct, invoke function,
4879 // and any copy/dispose helper functions.
4880 InsertBlockLiteralsWithinFunction(FD);
4881 CurFunctionDef = 0;
4882 CurFunctionDeclToDeclareForBlock = 0;
4883 }
4884 break;
4885 }
4886 case Decl::ObjCMethod: {
4887 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4888 if (CompoundStmt *Body = MD->getCompoundBody()) {
4889 CurMethodDef = MD;
4890 CurrentBody = Body;
4891 Body =
4892 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4893 MD->setBody(Body);
4894 CurrentBody = 0;
4895 if (PropParentMap) {
4896 delete PropParentMap;
4897 PropParentMap = 0;
4898 }
4899 InsertBlockLiteralsWithinMethod(MD);
4900 CurMethodDef = 0;
4901 }
4902 break;
4903 }
4904 case Decl::ObjCImplementation: {
4905 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4906 ClassImplementation.push_back(CI);
4907 break;
4908 }
4909 case Decl::ObjCCategoryImpl: {
4910 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4911 CategoryImplementation.push_back(CI);
4912 break;
4913 }
4914 case Decl::Var: {
4915 VarDecl *VD = cast<VarDecl>(D);
4916 RewriteObjCQualifiedInterfaceTypes(VD);
4917 if (isTopLevelBlockPointerType(VD->getType()))
4918 RewriteBlockPointerDecl(VD);
4919 else if (VD->getType()->isFunctionPointerType()) {
4920 CheckFunctionPointerDecl(VD->getType(), VD);
4921 if (VD->getInit()) {
4922 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4923 RewriteCastExpr(CE);
4924 }
4925 }
4926 } else if (VD->getType()->isRecordType()) {
4927 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4928 if (RD->isCompleteDefinition())
4929 RewriteRecordBody(RD);
4930 }
4931 if (VD->getInit()) {
4932 GlobalVarDecl = VD;
4933 CurrentBody = VD->getInit();
4934 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4935 CurrentBody = 0;
4936 if (PropParentMap) {
4937 delete PropParentMap;
4938 PropParentMap = 0;
4939 }
4940 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4941 GlobalVarDecl = 0;
4942
4943 // This is needed for blocks.
4944 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4945 RewriteCastExpr(CE);
4946 }
4947 }
4948 break;
4949 }
4950 case Decl::TypeAlias:
4951 case Decl::Typedef: {
4952 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4953 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4954 RewriteBlockPointerDecl(TD);
4955 else if (TD->getUnderlyingType()->isFunctionPointerType())
4956 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4957 }
4958 break;
4959 }
4960 case Decl::CXXRecord:
4961 case Decl::Record: {
4962 RecordDecl *RD = cast<RecordDecl>(D);
4963 if (RD->isCompleteDefinition())
4964 RewriteRecordBody(RD);
4965 break;
4966 }
4967 default:
4968 break;
4969 }
4970 // Nothing yet.
4971}
4972
4973void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
4974 if (Diags.hasErrorOccurred())
4975 return;
4976
4977 RewriteInclude();
4978
4979 // Here's a great place to add any extra declarations that may be needed.
4980 // Write out meta data for each @protocol(<expr>).
4981 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
4982 E = ProtocolExprDecls.end(); I != E; ++I)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00004983 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004984
4985 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
4986 if (ClassImplementation.size() || CategoryImplementation.size())
4987 RewriteImplementations();
4988
4989 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4990 // we are done.
4991 if (const RewriteBuffer *RewriteBuf =
4992 Rewrite.getRewriteBufferFor(MainFileID)) {
4993 //printf("Changed:\n");
4994 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4995 } else {
4996 llvm::errs() << "No changes\n";
4997 }
4998
4999 if (ClassImplementation.size() || CategoryImplementation.size() ||
5000 ProtocolExprDecls.size()) {
5001 // Rewrite Objective-c meta data*
5002 std::string ResultStr;
5003 RewriteMetaDataIntoBuffer(ResultStr);
5004 // Emit metadata.
5005 *OutFile << ResultStr;
5006 }
5007 OutFile->flush();
5008}
5009
5010void RewriteModernObjC::Initialize(ASTContext &context) {
5011 InitializeCommon(context);
5012
5013 // declaring objc_selector outside the parameter list removes a silly
5014 // scope related warning...
5015 if (IsHeader)
5016 Preamble = "#pragma once\n";
5017 Preamble += "struct objc_selector; struct objc_class;\n";
5018 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5019 Preamble += "struct objc_object *superClass; ";
5020 if (LangOpts.MicrosoftExt) {
5021 // Add a constructor for creating temporary objects.
5022 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5023 ": ";
5024 Preamble += "object(o), superClass(s) {} ";
5025 }
5026 Preamble += "};\n";
5027 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5028 Preamble += "typedef struct objc_object Protocol;\n";
5029 Preamble += "#define _REWRITER_typedef_Protocol\n";
5030 Preamble += "#endif\n";
5031 if (LangOpts.MicrosoftExt) {
5032 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5033 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5034 } else
5035 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5036 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5037 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5038 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5039 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5040 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5041 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5042 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5043 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5044 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5045 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5046 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5047 Preamble += "(const char *);\n";
5048 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5049 Preamble += "(struct objc_class *);\n";
5050 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5051 Preamble += "(const char *);\n";
5052 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5053 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5054 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5055 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5056 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5057 Preamble += "(struct objc_class *, struct objc_object *);\n";
5058 // @synchronized hooks.
5059 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
5060 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
5061 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5062 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5063 Preamble += "struct __objcFastEnumerationState {\n\t";
5064 Preamble += "unsigned long state;\n\t";
5065 Preamble += "void **itemsPtr;\n\t";
5066 Preamble += "unsigned long *mutationsPtr;\n\t";
5067 Preamble += "unsigned long extra[5];\n};\n";
5068 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5069 Preamble += "#define __FASTENUMERATIONSTATE\n";
5070 Preamble += "#endif\n";
5071 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5072 Preamble += "struct __NSConstantStringImpl {\n";
5073 Preamble += " int *isa;\n";
5074 Preamble += " int flags;\n";
5075 Preamble += " char *str;\n";
5076 Preamble += " long length;\n";
5077 Preamble += "};\n";
5078 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5079 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5080 Preamble += "#else\n";
5081 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5082 Preamble += "#endif\n";
5083 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5084 Preamble += "#endif\n";
5085 // Blocks preamble.
5086 Preamble += "#ifndef BLOCK_IMPL\n";
5087 Preamble += "#define BLOCK_IMPL\n";
5088 Preamble += "struct __block_impl {\n";
5089 Preamble += " void *isa;\n";
5090 Preamble += " int Flags;\n";
5091 Preamble += " int Reserved;\n";
5092 Preamble += " void *FuncPtr;\n";
5093 Preamble += "};\n";
5094 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5095 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5096 Preamble += "extern \"C\" __declspec(dllexport) "
5097 "void _Block_object_assign(void *, const void *, const int);\n";
5098 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5099 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5100 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5101 Preamble += "#else\n";
5102 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5103 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5104 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5105 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5106 Preamble += "#endif\n";
5107 Preamble += "#endif\n";
5108 if (LangOpts.MicrosoftExt) {
5109 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5110 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5111 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5112 Preamble += "#define __attribute__(X)\n";
5113 Preamble += "#endif\n";
5114 Preamble += "#define __weak\n";
5115 }
5116 else {
5117 Preamble += "#define __block\n";
5118 Preamble += "#define __weak\n";
5119 }
5120 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5121 // as this avoids warning in any 64bit/32bit compilation model.
5122 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5123}
5124
5125/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5126/// ivar offset.
5127void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5128 std::string &Result) {
5129 if (ivar->isBitField()) {
5130 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5131 // place all bitfields at offset 0.
5132 Result += "0";
5133 } else {
5134 Result += "__OFFSETOFIVAR__(struct ";
5135 Result += ivar->getContainingInterface()->getNameAsString();
5136 if (LangOpts.MicrosoftExt)
5137 Result += "_IMPL";
5138 Result += ", ";
5139 Result += ivar->getNameAsString();
5140 Result += ")";
5141 }
5142}
5143
5144/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5145/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005146/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005147/// char *attributes;
5148/// }
5149
5150/// struct _prop_list_t {
5151/// uint32_t entsize; // sizeof(struct _prop_t)
5152/// uint32_t count_of_properties;
5153/// struct _prop_t prop_list[count_of_properties];
5154/// }
5155
5156/// struct _protocol_t;
5157
5158/// struct _protocol_list_t {
5159/// long protocol_count; // Note, this is 32/64 bit
5160/// struct _protocol_t * protocol_list[protocol_count];
5161/// }
5162
5163/// struct _objc_method {
5164/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005165/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005166/// char *_imp;
5167/// }
5168
5169/// struct _method_list_t {
5170/// uint32_t entsize; // sizeof(struct _objc_method)
5171/// uint32_t method_count;
5172/// struct _objc_method method_list[method_count];
5173/// }
5174
5175/// struct _protocol_t {
5176/// id isa; // NULL
5177/// const char * const protocol_name;
5178/// const struct _protocol_list_t * protocol_list; // super protocols
5179/// const struct method_list_t * const instance_methods;
5180/// const struct method_list_t * const class_methods;
5181/// const struct method_list_t *optionalInstanceMethods;
5182/// const struct method_list_t *optionalClassMethods;
5183/// const struct _prop_list_t * properties;
5184/// const uint32_t size; // sizeof(struct _protocol_t)
5185/// const uint32_t flags; // = 0
5186/// const char ** extendedMethodTypes;
5187/// }
5188
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005189/// struct _ivar_t {
5190/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005191/// const char *name;
5192/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005193/// uint32_t alignment;
5194/// uint32_t size;
5195/// }
5196
5197/// struct _ivar_list_t {
5198/// uint32 entsize; // sizeof(struct _ivar_t)
5199/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005200/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005201/// }
5202
5203/// struct _class_ro_t {
5204/// uint32_t const flags;
5205/// uint32_t const instanceStart;
5206/// uint32_t const instanceSize;
5207/// uint32_t const reserved; // only when building for 64bit targets
5208/// const uint8_t * const ivarLayout;
5209/// const char *const name;
5210/// const struct _method_list_t * const baseMethods;
5211/// const struct _objc_protocol_list *const baseProtocols;
5212/// const struct _ivar_list_t *const ivars;
5213/// const uint8_t * const weakIvarLayout;
5214/// const struct _prop_list_t * const properties;
5215/// }
5216
5217/// struct _class_t {
5218/// struct _class_t *isa;
5219/// struct _class_t * const superclass;
5220/// void *cache;
5221/// IMP *vtable;
5222/// struct class_ro_t *ro;
5223/// }
5224
5225/// struct _category_t {
5226/// const char * const name;
5227/// struct _class_t *const cls;
5228/// const struct _method_list_t * const instance_methods;
5229/// const struct _method_list_t * const class_methods;
5230/// const struct _protocol_list_t * const protocols;
5231/// const struct _prop_list_t * const properties;
5232/// }
5233
5234/// MessageRefTy - LLVM for:
5235/// struct _message_ref_t {
5236/// IMP messenger;
5237/// SEL name;
5238/// };
5239
5240/// SuperMessageRefTy - LLVM for:
5241/// struct _super_message_ref_t {
5242/// SUPER_IMP messenger;
5243/// SEL name;
5244/// };
5245
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005246static void WriteModernMetadataDeclarations(std::string &Result) {
5247 static bool meta_data_declared = false;
5248 if (meta_data_declared)
5249 return;
5250
5251 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005252 Result += "\tconst char *name;\n";
5253 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005254 Result += "};\n";
5255
5256 Result += "\nstruct _protocol_t;\n";
5257
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005258 Result += "\nstruct _objc_method {\n";
5259 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005260 Result += "\tconst char *method_type;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005261 Result += "\tchar *_imp;\n";
5262 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005263
5264 Result += "\nstruct _protocol_t {\n";
5265 Result += "\tvoid * isa; // NULL\n";
5266 Result += "\tconst char * const protocol_name;\n";
5267 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
5268 Result += "\tconst struct method_list_t * const instance_methods;\n";
5269 Result += "\tconst struct method_list_t * const class_methods;\n";
5270 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5271 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5272 Result += "\tconst struct _prop_list_t * properties;\n";
5273 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5274 Result += "\tconst unsigned int flags; // = 0\n";
5275 Result += "\tconst char ** extendedMethodTypes;\n";
5276 Result += "};\n";
5277
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005278 Result += "\nstruct _ivar_t {\n";
5279 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005280 Result += "\tconst char *name;\n";
5281 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005282 Result += "\tunsigned int alignment;\n";
5283 Result += "\tunsigned int size;\n";
5284 Result += "};\n";
5285
5286 Result += "\nstruct _class_ro_t {\n";
5287 Result += "\tunsigned int const flags;\n";
5288 Result += "\tunsigned int instanceStart;\n";
5289 Result += "\tunsigned int const instanceSize;\n";
5290 Result += "\tunsigned int const reserved; // only when building for 64bit targets\n";
5291 Result += "\tconst unsigned char * const ivarLayout;\n";
5292 Result += "\tconst char *const name;\n";
5293 Result += "\tconst struct _method_list_t * const baseMethods;\n";
5294 Result += "\tconst struct _objc_protocol_list *const baseProtocols;\n";
5295 Result += "\tconst struct _ivar_list_t *const ivars;\n";
5296 Result += "\tconst unsigned char *const weakIvarLayout;\n";
5297 Result += "\tconst struct _prop_list_t *const properties;\n";
5298 Result += "};\n";
5299
5300 Result += "\nstruct _class_t {\n";
5301 Result += "\tstruct _class_t *isa;\n";
5302 Result += "\tstruct _class_t *const superclass;\n";
5303 Result += "\tvoid *cache;\n";
5304 Result += "\tvoid *vtable;\n";
5305 Result += "\tstruct class_ro_t *ro;\n";
5306 Result += "};\n";
5307
5308 Result += "\nstruct _category_t {\n";
5309 Result += "\tconst char * const name;\n";
5310 Result += "\tstruct _class_t *const cls;\n";
5311 Result += "\tconst struct _method_list_t *const instance_methods;\n";
5312 Result += "\tconst struct _method_list_t *const class_methods;\n";
5313 Result += "\tconst struct _protocol_list_t *const protocols;\n";
5314 Result += "\tconst struct _prop_list_t *const properties;\n";
5315 Result += "};\n";
5316
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005317 meta_data_declared = true;
5318}
5319
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005320static void Write_protocol_list_t_TypeDecl(std::string &Result,
5321 long super_protocol_count) {
5322 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5323 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5324 Result += "\tstruct _protocol_t *super_protocols[";
5325 Result += utostr(super_protocol_count); Result += "];\n";
5326 Result += "}";
5327}
5328
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005329static void Write_method_list_t_TypeDecl(std::string &Result,
5330 unsigned int method_count) {
5331 Result += "struct /*_method_list_t*/"; Result += " {\n";
5332 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5333 Result += "\tunsigned int method_count;\n";
5334 Result += "\tstruct _objc_method method_list[";
5335 Result += utostr(method_count); Result += "];\n";
5336 Result += "}";
5337}
5338
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005339static void Write__prop_list_t_TypeDecl(std::string &Result,
5340 unsigned int property_count) {
5341 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5342 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5343 Result += "\tunsigned int count_of_properties;\n";
5344 Result += "\tstruct _prop_t prop_list[";
5345 Result += utostr(property_count); Result += "];\n";
5346 Result += "}";
5347}
5348
Fariborz Jahanianae932952012-02-10 20:47:10 +00005349static void Write__ivar_list_t_TypeDecl(std::string &Result,
5350 unsigned int ivar_count) {
5351 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5352 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5353 Result += "\tunsigned int count;\n";
5354 Result += "\tstruct _ivar_t ivar_list[";
5355 Result += utostr(ivar_count); Result += "];\n";
5356 Result += "}";
5357}
5358
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005359static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5360 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5361 StringRef VarName,
5362 StringRef ProtocolName) {
5363 if (SuperProtocols.size() > 0) {
5364 Result += "\nstatic ";
5365 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5366 Result += " "; Result += VarName;
5367 Result += ProtocolName;
5368 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5369 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5370 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5371 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5372 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5373 Result += SuperPD->getNameAsString();
5374 if (i == e-1)
5375 Result += "\n};\n";
5376 else
5377 Result += ",\n";
5378 }
5379 }
5380}
5381
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005382static void Write_method_list_t_initializer(ASTContext *Context, std::string &Result,
5383 ArrayRef<ObjCMethodDecl *> Methods,
5384 StringRef VarName,
5385 StringRef ProtocolName) {
5386 if (Methods.size() > 0) {
5387 Result += "\nstatic ";
5388 Write_method_list_t_TypeDecl(Result, Methods.size());
5389 Result += " "; Result += VarName;
5390 Result += ProtocolName;
5391 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5392 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
5393 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
5394 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5395 ObjCMethodDecl *MD = Methods[i];
5396 if (i == 0)
5397 Result += "\t{{(struct objc_selector *)\"";
5398 else
5399 Result += "\t{(struct objc_selector *)\"";
5400 Result += (MD)->getSelector().getAsString(); Result += "\"";
5401 Result += ", ";
5402 std::string MethodTypeString;
5403 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
5404 Result += "\""; Result += MethodTypeString; Result += "\"";
5405 Result += ", ";
5406 // FIXME is _imp always null here?
5407 if (i == e-1)
5408 Result += "0}}\n";
5409 else
5410 Result += "0},\n";
5411 }
5412 Result += "};\n";
5413 }
5414}
5415
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005416static void Write__prop_list_t_initializer(RewriteModernObjC &RewriteObj,
5417 ASTContext *Context, std::string &Result,
5418 ArrayRef<ObjCPropertyDecl *> Properties,
5419 const Decl *Container,
5420 StringRef VarName,
5421 StringRef ProtocolName) {
5422 if (Properties.size() > 0) {
5423 Result += "\nstatic ";
5424 Write__prop_list_t_TypeDecl(Result, Properties.size());
5425 Result += " "; Result += VarName;
5426 Result += ProtocolName;
5427 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5428 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
5429 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
5430 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
5431 ObjCPropertyDecl *PropDecl = Properties[i];
5432 if (i == 0)
5433 Result += "\t{{\"";
5434 else
5435 Result += "\t{\"";
5436 Result += PropDecl->getName(); Result += "\",";
5437 std::string PropertyTypeString, QuotePropertyTypeString;
5438 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
5439 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
5440 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
5441 if (i == e-1)
5442 Result += "}}\n";
5443 else
5444 Result += "},\n";
5445 }
5446 Result += "};\n";
5447 }
5448}
5449
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005450static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
5451 ASTContext *Context, std::string &Result,
5452 ArrayRef<ObjCMethodDecl *> Methods,
5453 StringRef VarName,
5454 StringRef ProtocolName) {
5455 if (Methods.size() == 0)
5456 return;
5457
5458 Result += "\nstatic const char *";
5459 Result += VarName; Result += ProtocolName;
5460 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5461 Result += "{\n";
5462 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5463 ObjCMethodDecl *MD = Methods[i];
5464 std::string MethodTypeString, QuoteMethodTypeString;
5465 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
5466 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
5467 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
5468 if (i == e-1)
5469 Result += "\n};\n";
5470 else {
5471 Result += ",\n";
5472 }
5473 }
5474}
5475
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005476static void Write_IvarOffsetVar(std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005477 ArrayRef<ObjCIvarDecl *> Ivars,
5478 StringRef VarName,
5479 StringRef ClassName) {
5480 // FIXME. visibilty of offset symbols may have to be set; for Darwin
5481 // this is what happens:
5482 /**
5483 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
5484 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
5485 Class->getVisibility() == HiddenVisibility)
5486 Visibility shoud be: HiddenVisibility;
5487 else
5488 Visibility shoud be: DefaultVisibility;
5489 */
5490
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005491 Result += "\n";
5492 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5493 ObjCIvarDecl *IvarDecl = Ivars[i];
5494 Result += "unsigned long int "; Result += VarName;
5495 Result += ClassName; Result += "_";
5496 Result += IvarDecl->getName();
5497 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
5498 Result += " = ";
5499 if (IvarDecl->isBitField()) {
5500 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5501 // place all bitfields at offset 0.
5502 Result += "0;\n";
5503 }
5504 else {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005505 Result += "__OFFSETOFIVAR__(struct ";
5506 Result += ClassName;
5507 Result += "_IMPL, ";
5508 Result += IvarDecl->getName(); Result += ");\n";
5509 }
5510 }
5511}
5512
Fariborz Jahanianae932952012-02-10 20:47:10 +00005513static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
5514 ASTContext *Context, std::string &Result,
5515 ArrayRef<ObjCIvarDecl *> Ivars,
5516 StringRef VarName,
5517 StringRef ClassName) {
5518 if (Ivars.size() > 0) {
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005519 Write_IvarOffsetVar(Result, Ivars, "OBJC_IVAR_$_", ClassName);
5520
Fariborz Jahanianae932952012-02-10 20:47:10 +00005521 Result += "\nstatic ";
5522 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
5523 Result += " "; Result += VarName;
5524 Result += ClassName;
5525 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5526 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
5527 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
5528 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5529 ObjCIvarDecl *IvarDecl = Ivars[i];
5530 if (i == 0)
5531 Result += "\t{{";
5532 else
5533 Result += "\t {";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005534
5535 Result += "(unsigned long int *)&OBJC_IVAR_$_";
5536 Result += ClassName; Result += "_"; Result += IvarDecl->getName();
5537 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005538
5539 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
5540 std::string IvarTypeString, QuoteIvarTypeString;
5541 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
5542 IvarDecl);
5543 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
5544 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
5545
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00005546 // FIXME. this alignment represents the host alignment and need be changed to
5547 // represent the target alignment.
5548 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
5549 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00005550 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00005551 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
5552 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00005553 if (i == e-1)
5554 Result += "}}\n";
5555 else
5556 Result += "},\n";
5557 }
5558 Result += "};\n";
5559 }
5560}
5561
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005562/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005563void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
5564 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005565
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005566 // Do not synthesize the protocol more than once.
5567 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
5568 return;
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005569 WriteModernMetadataDeclarations(Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005570
5571 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5572 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005573 // Must write out all protocol definitions in current qualifier list,
5574 // and in their nested qualifiers before writing out current definition.
5575 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5576 E = PDecl->protocol_end(); I != E; ++I)
5577 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005578
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005579 // Construct method lists.
5580 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
5581 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
5582 for (ObjCProtocolDecl::instmeth_iterator
5583 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5584 I != E; ++I) {
5585 ObjCMethodDecl *MD = *I;
5586 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5587 OptInstanceMethods.push_back(MD);
5588 } else {
5589 InstanceMethods.push_back(MD);
5590 }
5591 }
5592
5593 for (ObjCProtocolDecl::classmeth_iterator
5594 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5595 I != E; ++I) {
5596 ObjCMethodDecl *MD = *I;
5597 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5598 OptClassMethods.push_back(MD);
5599 } else {
5600 ClassMethods.push_back(MD);
5601 }
5602 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005603 std::vector<ObjCMethodDecl *> AllMethods;
5604 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
5605 AllMethods.push_back(InstanceMethods[i]);
5606 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
5607 AllMethods.push_back(ClassMethods[i]);
5608 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
5609 AllMethods.push_back(OptInstanceMethods[i]);
5610 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
5611 AllMethods.push_back(OptClassMethods[i]);
5612
5613 Write__extendedMethodTypes_initializer(*this, Context, Result,
5614 AllMethods,
5615 "_OBJC_PROTOCOL_METHOD_TYPES_",
5616 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005617 // Protocol's super protocol list
5618 std::vector<ObjCProtocolDecl *> SuperProtocols;
5619 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5620 E = PDecl->protocol_end(); I != E; ++I)
5621 SuperProtocols.push_back(*I);
5622
5623 Write_protocol_list_initializer(Context, Result, SuperProtocols,
5624 "_OBJC_PROTOCOL_REFS_",
5625 PDecl->getNameAsString());
5626
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005627 Write_method_list_t_initializer(Context, Result, InstanceMethods,
5628 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
5629 PDecl->getNameAsString());
5630
5631 Write_method_list_t_initializer(Context, Result, ClassMethods,
5632 "_OBJC_PROTOCOL_CLASS_METHODS_",
5633 PDecl->getNameAsString());
5634
5635 Write_method_list_t_initializer(Context, Result, OptInstanceMethods,
5636 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
5637 PDecl->getNameAsString());
5638
5639 Write_method_list_t_initializer(Context, Result, OptClassMethods,
5640 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
5641 PDecl->getNameAsString());
5642
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005643 // Protocol's property metadata.
5644 std::vector<ObjCPropertyDecl *> ProtocolProperties;
5645 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
5646 E = PDecl->prop_end(); I != E; ++I)
5647 ProtocolProperties.push_back(*I);
5648
5649 Write__prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
5650 /* Container */0,
5651 "_OBJC_PROTOCOL_PROPERTIES_",
5652 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005653
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005654 // Writer out root metadata for current protocol: struct _protocol_t
5655 Result += "\nstatic struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005656 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005657 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
5658 Result += "\t0,\n"; // id is; is null
5659 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005660 if (SuperProtocols.size() > 0) {
5661 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
5662 Result += PDecl->getNameAsString(); Result += ",\n";
5663 }
5664 else
5665 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005666 if (InstanceMethods.size() > 0) {
5667 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5668 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005669 }
5670 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005671 Result += "\t0,\n";
5672
5673 if (ClassMethods.size() > 0) {
5674 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5675 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005676 }
5677 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005678 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005679
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005680 if (OptInstanceMethods.size() > 0) {
5681 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
5682 Result += PDecl->getNameAsString(); Result += ",\n";
5683 }
5684 else
5685 Result += "\t0,\n";
5686
5687 if (OptClassMethods.size() > 0) {
5688 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
5689 Result += PDecl->getNameAsString(); Result += ",\n";
5690 }
5691 else
5692 Result += "\t0,\n";
5693
5694 if (ProtocolProperties.size() > 0) {
5695 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
5696 Result += PDecl->getNameAsString(); Result += ",\n";
5697 }
5698 else
5699 Result += "\t0,\n";
5700
5701 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
5702 Result += "\t0,\n";
5703
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005704 if (AllMethods.size() > 0) {
5705 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
5706 Result += PDecl->getNameAsString();
5707 Result += "\n};\n";
5708 }
5709 else
5710 Result += "\t0\n};\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005711
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005712 // Mark this protocol as having been generated.
5713 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
5714 llvm_unreachable("protocol already synthesized");
5715
5716}
5717
5718void RewriteModernObjC::RewriteObjCProtocolListMetaData(
5719 const ObjCList<ObjCProtocolDecl> &Protocols,
5720 StringRef prefix, StringRef ClassName,
5721 std::string &Result) {
5722 if (Protocols.empty()) return;
5723
5724 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005725 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005726
5727 // Output the top lovel protocol meta-data for the class.
5728 /* struct _objc_protocol_list {
5729 struct _objc_protocol_list *next;
5730 int protocol_count;
5731 struct _objc_protocol *class_protocols[];
5732 }
5733 */
5734 Result += "\nstatic struct {\n";
5735 Result += "\tstruct _objc_protocol_list *next;\n";
5736 Result += "\tint protocol_count;\n";
5737 Result += "\tstruct _objc_protocol *class_protocols[";
5738 Result += utostr(Protocols.size());
5739 Result += "];\n} _OBJC_";
5740 Result += prefix;
5741 Result += "_PROTOCOLS_";
5742 Result += ClassName;
5743 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5744 "{\n\t0, ";
5745 Result += utostr(Protocols.size());
5746 Result += "\n";
5747
5748 Result += "\t,{&_OBJC_PROTOCOL_";
5749 Result += Protocols[0]->getNameAsString();
5750 Result += " \n";
5751
5752 for (unsigned i = 1; i != Protocols.size(); i++) {
5753 Result += "\t ,&_OBJC_PROTOCOL_";
5754 Result += Protocols[i]->getNameAsString();
5755 Result += "\n";
5756 }
5757 Result += "\t }\n};\n";
5758}
5759
5760void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5761 std::string &Result) {
5762 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5763
5764 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00005765 if (CDecl->isImplicitInterfaceDecl())
5766 assert(false &&
5767 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00005768
Fariborz Jahanianae932952012-02-10 20:47:10 +00005769 WriteModernMetadataDeclarations(Result);
5770 SmallVector<ObjCIvarDecl *, 8> IVars;
5771
5772 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
5773 IVD; IVD = IVD->getNextIvar()) {
5774 // Ignore unnamed bit-fields.
5775 if (!IVD->getDeclName())
5776 continue;
5777 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005778 }
5779
Fariborz Jahanianae932952012-02-10 20:47:10 +00005780 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
5781 "_OBJC_INSTANCE_VARIABLES_",
5782 CDecl->getNameAsString());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005783}
5784
5785void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
5786 int ClsDefCount = ClassImplementation.size();
5787 int CatDefCount = CategoryImplementation.size();
5788
5789 // For each implemented class, write out all its meta data.
5790 for (int i = 0; i < ClsDefCount; i++)
5791 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5792
5793 // For each implemented category, write out all its meta data.
5794 for (int i = 0; i < CatDefCount; i++)
5795 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5796
5797 // Write objc_symtab metadata
5798 /*
5799 struct _objc_symtab
5800 {
5801 long sel_ref_cnt;
5802 SEL *refs;
5803 short cls_def_cnt;
5804 short cat_def_cnt;
5805 void *defs[cls_def_cnt + cat_def_cnt];
5806 };
5807 */
5808
5809 Result += "\nstruct _objc_symtab {\n";
5810 Result += "\tlong sel_ref_cnt;\n";
5811 Result += "\tSEL *refs;\n";
5812 Result += "\tshort cls_def_cnt;\n";
5813 Result += "\tshort cat_def_cnt;\n";
5814 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5815 Result += "};\n\n";
5816
5817 Result += "static struct _objc_symtab "
5818 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5819 Result += "\t0, 0, " + utostr(ClsDefCount)
5820 + ", " + utostr(CatDefCount) + "\n";
5821 for (int i = 0; i < ClsDefCount; i++) {
5822 Result += "\t,&_OBJC_CLASS_";
5823 Result += ClassImplementation[i]->getNameAsString();
5824 Result += "\n";
5825 }
5826
5827 for (int i = 0; i < CatDefCount; i++) {
5828 Result += "\t,&_OBJC_CATEGORY_";
5829 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5830 Result += "_";
5831 Result += CategoryImplementation[i]->getNameAsString();
5832 Result += "\n";
5833 }
5834
5835 Result += "};\n\n";
5836
5837 // Write objc_module metadata
5838
5839 /*
5840 struct _objc_module {
5841 long version;
5842 long size;
5843 const char *name;
5844 struct _objc_symtab *symtab;
5845 }
5846 */
5847
5848 Result += "\nstruct _objc_module {\n";
5849 Result += "\tlong version;\n";
5850 Result += "\tlong size;\n";
5851 Result += "\tconst char *name;\n";
5852 Result += "\tstruct _objc_symtab *symtab;\n";
5853 Result += "};\n\n";
5854 Result += "static struct _objc_module "
5855 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5856 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5857 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5858 Result += "};\n\n";
5859
5860 if (LangOpts.MicrosoftExt) {
5861 if (ProtocolExprDecls.size()) {
5862 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5863 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5864 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5865 E = ProtocolExprDecls.end(); I != E; ++I) {
5866 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5867 Result += (*I)->getNameAsString();
5868 Result += " = &_OBJC_PROTOCOL_";
5869 Result += (*I)->getNameAsString();
5870 Result += ";\n";
5871 }
5872 Result += "#pragma data_seg(pop)\n\n";
5873 }
5874 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5875 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5876 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5877 Result += "&_OBJC_MODULES;\n";
5878 Result += "#pragma data_seg(pop)\n\n";
5879 }
5880}
5881
5882/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5883/// implementation.
5884void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5885 std::string &Result) {
5886 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5887 // Find category declaration for this implementation.
5888 ObjCCategoryDecl *CDecl;
5889 for (CDecl = ClassDecl->getCategoryList(); CDecl;
5890 CDecl = CDecl->getNextClassCategory())
5891 if (CDecl->getIdentifier() == IDecl->getIdentifier())
5892 break;
5893
5894 std::string FullCategoryName = ClassDecl->getNameAsString();
5895 FullCategoryName += '_';
5896 FullCategoryName += IDecl->getNameAsString();
5897
5898 // Build _objc_method_list for class's instance methods if needed
5899 SmallVector<ObjCMethodDecl *, 32>
5900 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5901
5902 // If any of our property implementations have associated getters or
5903 // setters, produce metadata for them as well.
5904 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5905 PropEnd = IDecl->propimpl_end();
5906 Prop != PropEnd; ++Prop) {
5907 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5908 continue;
5909 if (!(*Prop)->getPropertyIvarDecl())
5910 continue;
5911 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
5912 if (!PD)
5913 continue;
5914 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5915 InstanceMethods.push_back(Getter);
5916 if (PD->isReadOnly())
5917 continue;
5918 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5919 InstanceMethods.push_back(Setter);
5920 }
5921 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5922 true, "CATEGORY_", FullCategoryName.c_str(),
5923 Result);
5924
5925 // Build _objc_method_list for class's class methods if needed
5926 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5927 false, "CATEGORY_", FullCategoryName.c_str(),
5928 Result);
5929
5930 // Protocols referenced in class declaration?
5931 // Null CDecl is case of a category implementation with no category interface
5932 if (CDecl)
5933 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5934 FullCategoryName, Result);
5935 /* struct _objc_category {
5936 char *category_name;
5937 char *class_name;
5938 struct _objc_method_list *instance_methods;
5939 struct _objc_method_list *class_methods;
5940 struct _objc_protocol_list *protocols;
5941 // Objective-C 1.0 extensions
5942 uint32_t size; // sizeof (struct _objc_category)
5943 struct _objc_property_list *instance_properties; // category's own
5944 // @property decl.
5945 };
5946 */
5947
5948 static bool objc_category = false;
5949 if (!objc_category) {
5950 Result += "\nstruct _objc_category {\n";
5951 Result += "\tchar *category_name;\n";
5952 Result += "\tchar *class_name;\n";
5953 Result += "\tstruct _objc_method_list *instance_methods;\n";
5954 Result += "\tstruct _objc_method_list *class_methods;\n";
5955 Result += "\tstruct _objc_protocol_list *protocols;\n";
5956 Result += "\tunsigned int size;\n";
5957 Result += "\tstruct _objc_property_list *instance_properties;\n";
5958 Result += "};\n";
5959 objc_category = true;
5960 }
5961 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5962 Result += FullCategoryName;
5963 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5964 Result += IDecl->getNameAsString();
5965 Result += "\"\n\t, \"";
5966 Result += ClassDecl->getNameAsString();
5967 Result += "\"\n";
5968
5969 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5970 Result += "\t, (struct _objc_method_list *)"
5971 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5972 Result += FullCategoryName;
5973 Result += "\n";
5974 }
5975 else
5976 Result += "\t, 0\n";
5977 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5978 Result += "\t, (struct _objc_method_list *)"
5979 "&_OBJC_CATEGORY_CLASS_METHODS_";
5980 Result += FullCategoryName;
5981 Result += "\n";
5982 }
5983 else
5984 Result += "\t, 0\n";
5985
5986 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5987 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5988 Result += FullCategoryName;
5989 Result += "\n";
5990 }
5991 else
5992 Result += "\t, 0\n";
5993 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5994}
5995
5996// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5997/// class methods.
5998template<typename MethodIterator>
5999void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
6000 MethodIterator MethodEnd,
6001 bool IsInstanceMethod,
6002 StringRef prefix,
6003 StringRef ClassName,
6004 std::string &Result) {
6005 if (MethodBegin == MethodEnd) return;
6006
6007 if (!objc_impl_method) {
6008 /* struct _objc_method {
6009 SEL _cmd;
6010 char *method_types;
6011 void *_imp;
6012 }
6013 */
6014 Result += "\nstruct _objc_method {\n";
6015 Result += "\tSEL _cmd;\n";
6016 Result += "\tchar *method_types;\n";
6017 Result += "\tvoid *_imp;\n";
6018 Result += "};\n";
6019
6020 objc_impl_method = true;
6021 }
6022
6023 // Build _objc_method_list for class's methods if needed
6024
6025 /* struct {
6026 struct _objc_method_list *next_method;
6027 int method_count;
6028 struct _objc_method method_list[];
6029 }
6030 */
6031 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
6032 Result += "\nstatic struct {\n";
6033 Result += "\tstruct _objc_method_list *next_method;\n";
6034 Result += "\tint method_count;\n";
6035 Result += "\tstruct _objc_method method_list[";
6036 Result += utostr(NumMethods);
6037 Result += "];\n} _OBJC_";
6038 Result += prefix;
6039 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
6040 Result += "_METHODS_";
6041 Result += ClassName;
6042 Result += " __attribute__ ((used, section (\"__OBJC, __";
6043 Result += IsInstanceMethod ? "inst" : "cls";
6044 Result += "_meth\")))= ";
6045 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
6046
6047 Result += "\t,{{(SEL)\"";
6048 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6049 std::string MethodTypeString;
6050 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6051 Result += "\", \"";
6052 Result += MethodTypeString;
6053 Result += "\", (void *)";
6054 Result += MethodInternalNames[*MethodBegin];
6055 Result += "}\n";
6056 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
6057 Result += "\t ,{(SEL)\"";
6058 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6059 std::string MethodTypeString;
6060 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6061 Result += "\", \"";
6062 Result += MethodTypeString;
6063 Result += "\", (void *)";
6064 Result += MethodInternalNames[*MethodBegin];
6065 Result += "}\n";
6066 }
6067 Result += "\t }\n};\n";
6068}
6069
6070Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
6071 SourceRange OldRange = IV->getSourceRange();
6072 Expr *BaseExpr = IV->getBase();
6073
6074 // Rewrite the base, but without actually doing replaces.
6075 {
6076 DisableReplaceStmtScope S(*this);
6077 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
6078 IV->setBase(BaseExpr);
6079 }
6080
6081 ObjCIvarDecl *D = IV->getDecl();
6082
6083 Expr *Replacement = IV;
6084 if (CurMethodDef) {
6085 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6086 const ObjCInterfaceType *iFaceDecl =
6087 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6088 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
6089 // lookup which class implements the instance variable.
6090 ObjCInterfaceDecl *clsDeclared = 0;
6091 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6092 clsDeclared);
6093 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6094
6095 // Synthesize an explicit cast to gain access to the ivar.
6096 std::string RecName = clsDeclared->getIdentifier()->getName();
6097 RecName += "_IMPL";
6098 IdentifierInfo *II = &Context->Idents.get(RecName);
6099 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
6100 SourceLocation(), SourceLocation(),
6101 II);
6102 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
6103 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
6104 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
6105 CK_BitCast,
6106 IV->getBase());
6107 // Don't forget the parens to enforce the proper binding.
6108 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
6109 OldRange.getEnd(),
6110 castExpr);
6111 if (IV->isFreeIvar() &&
6112 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
6113 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
6114 IV->getLocation(),
6115 D->getType(),
6116 VK_LValue, OK_Ordinary);
6117 Replacement = ME;
6118 } else {
6119 IV->setBase(PE);
6120 }
6121 }
6122 } else { // we are outside a method.
6123 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
6124
6125 // Explicit ivar refs need to have a cast inserted.
6126 // FIXME: consider sharing some of this code with the code above.
6127 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6128 const ObjCInterfaceType *iFaceDecl =
6129 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6130 // lookup which class implements the instance variable.
6131 ObjCInterfaceDecl *clsDeclared = 0;
6132 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6133 clsDeclared);
6134 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6135
6136 // Synthesize an explicit cast to gain access to the ivar.
6137 std::string RecName = clsDeclared->getIdentifier()->getName();
6138 RecName += "_IMPL";
6139 IdentifierInfo *II = &Context->Idents.get(RecName);
6140 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
6141 SourceLocation(), SourceLocation(),
6142 II);
6143 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
6144 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
6145 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
6146 CK_BitCast,
6147 IV->getBase());
6148 // Don't forget the parens to enforce the proper binding.
6149 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
6150 IV->getBase()->getLocEnd(), castExpr);
6151 // Cannot delete IV->getBase(), since PE points to it.
6152 // Replace the old base with the cast. This is important when doing
6153 // embedded rewrites. For example, [newInv->_container addObject:0].
6154 IV->setBase(PE);
6155 }
6156 }
6157
6158 ReplaceStmtWithRange(IV, Replacement, OldRange);
6159 return Replacement;
6160}
6161