1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 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 // This coordinates the per-module state used while generating code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenModule.h" 15 #include "CGDebugInfo.h" 16 #include "CodeGenFunction.h" 17 #include "CGCall.h" 18 #include "CGObjCRuntime.h" 19 #include "Mangle.h" 20 #include "clang/Frontend/CompileOptions.h" 21 #include "clang/AST/ASTContext.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclCXX.h" 24 #include "clang/Basic/Builtins.h" 25 #include "clang/Basic/Diagnostic.h" 26 #include "clang/Basic/SourceManager.h" 27 #include "clang/Basic/TargetInfo.h" 28 #include "clang/Basic/ConvertUTF.h" 29 #include "llvm/CallingConv.h" 30 #include "llvm/Module.h" 31 #include "llvm/Intrinsics.h" 32 #include "llvm/Target/TargetData.h" 33 #include "llvm/Support/ErrorHandling.h" 34 using namespace clang; 35 using namespace CodeGen; 36 37 38 CodeGenModule::CodeGenModule(ASTContext &C, const CompileOptions &compileOpts, 39 llvm::Module &M, const llvm::TargetData &TD, 40 Diagnostic &diags) 41 : BlockModule(C, M, TD, Types, *this), Context(C), 42 Features(C.getLangOptions()), CompileOpts(compileOpts), TheModule(M), 43 TheTargetData(TD), Diags(diags), Types(C, M, TD), MangleCtx(C), 44 VtableInfo(*this), Runtime(0), 45 MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0), 46 VMContext(M.getContext()) { 47 48 if (!Features.ObjC1) 49 Runtime = 0; 50 else if (!Features.NeXTRuntime) 51 Runtime = CreateGNUObjCRuntime(*this); 52 else if (Features.ObjCNonFragileABI) 53 Runtime = CreateMacNonFragileABIObjCRuntime(*this); 54 else 55 Runtime = CreateMacObjCRuntime(*this); 56 57 // If debug info generation is enabled, create the CGDebugInfo object. 58 DebugInfo = CompileOpts.DebugInfo ? new CGDebugInfo(this) : 0; 59 } 60 61 CodeGenModule::~CodeGenModule() { 62 delete Runtime; 63 delete DebugInfo; 64 } 65 66 void CodeGenModule::Release() { 67 // We need to call this first because it can add deferred declarations. 68 EmitCXXGlobalInitFunc(); 69 70 EmitDeferred(); 71 if (Runtime) 72 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction()) 73 AddGlobalCtor(ObjCInitFunction); 74 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 75 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 76 EmitAnnotations(); 77 EmitLLVMUsed(); 78 } 79 80 /// ErrorUnsupported - Print out an error that codegen doesn't support the 81 /// specified stmt yet. 82 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type, 83 bool OmitOnError) { 84 if (OmitOnError && getDiags().hasErrorOccurred()) 85 return; 86 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 87 "cannot compile this %0 yet"); 88 std::string Msg = Type; 89 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 90 << Msg << S->getSourceRange(); 91 } 92 93 /// ErrorUnsupported - Print out an error that codegen doesn't support the 94 /// specified decl yet. 95 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type, 96 bool OmitOnError) { 97 if (OmitOnError && getDiags().hasErrorOccurred()) 98 return; 99 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 100 "cannot compile this %0 yet"); 101 std::string Msg = Type; 102 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 103 } 104 105 LangOptions::VisibilityMode 106 CodeGenModule::getDeclVisibilityMode(const Decl *D) const { 107 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 108 if (VD->getStorageClass() == VarDecl::PrivateExtern) 109 return LangOptions::Hidden; 110 111 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) { 112 switch (attr->getVisibility()) { 113 default: assert(0 && "Unknown visibility!"); 114 case VisibilityAttr::DefaultVisibility: 115 return LangOptions::Default; 116 case VisibilityAttr::HiddenVisibility: 117 return LangOptions::Hidden; 118 case VisibilityAttr::ProtectedVisibility: 119 return LangOptions::Protected; 120 } 121 } 122 123 return getLangOptions().getVisibilityMode(); 124 } 125 126 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 127 const Decl *D) const { 128 // Internal definitions always have default visibility. 129 if (GV->hasLocalLinkage()) { 130 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 131 return; 132 } 133 134 switch (getDeclVisibilityMode(D)) { 135 default: assert(0 && "Unknown visibility!"); 136 case LangOptions::Default: 137 return GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 138 case LangOptions::Hidden: 139 return GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 140 case LangOptions::Protected: 141 return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 142 } 143 } 144 145 const char *CodeGenModule::getMangledName(const GlobalDecl &GD) { 146 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 147 148 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND)) 149 return getMangledCXXCtorName(D, GD.getCtorType()); 150 if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND)) 151 return getMangledCXXDtorName(D, GD.getDtorType()); 152 153 return getMangledName(ND); 154 } 155 156 /// \brief Retrieves the mangled name for the given declaration. 157 /// 158 /// If the given declaration requires a mangled name, returns an 159 /// const char* containing the mangled name. Otherwise, returns 160 /// the unmangled name. 161 /// 162 const char *CodeGenModule::getMangledName(const NamedDecl *ND) { 163 // In C, functions with no attributes never need to be mangled. Fastpath them. 164 if (!getLangOptions().CPlusPlus && !ND->hasAttrs()) { 165 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl."); 166 return ND->getNameAsCString(); 167 } 168 169 llvm::SmallString<256> Name; 170 llvm::raw_svector_ostream Out(Name); 171 if (!mangleName(getMangleContext(), ND, Out)) { 172 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl."); 173 return ND->getNameAsCString(); 174 } 175 176 Name += '\0'; 177 return UniqueMangledName(Name.begin(), Name.end()); 178 } 179 180 const char *CodeGenModule::UniqueMangledName(const char *NameStart, 181 const char *NameEnd) { 182 assert(*(NameEnd - 1) == '\0' && "Mangled name must be null terminated!"); 183 184 return MangledNames.GetOrCreateValue(NameStart, NameEnd).getKeyData(); 185 } 186 187 /// AddGlobalCtor - Add a function to the list that will be called before 188 /// main() runs. 189 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 190 // FIXME: Type coercion of void()* types. 191 GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 192 } 193 194 /// AddGlobalDtor - Add a function to the list that will be called 195 /// when the module is unloaded. 196 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 197 // FIXME: Type coercion of void()* types. 198 GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 199 } 200 201 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 202 // Ctor function type is void()*. 203 llvm::FunctionType* CtorFTy = 204 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), 205 std::vector<const llvm::Type*>(), 206 false); 207 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 208 209 // Get the type of a ctor entry, { i32, void ()* }. 210 llvm::StructType* CtorStructTy = 211 llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext), 212 llvm::PointerType::getUnqual(CtorFTy), NULL); 213 214 // Construct the constructor and destructor arrays. 215 std::vector<llvm::Constant*> Ctors; 216 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 217 std::vector<llvm::Constant*> S; 218 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 219 I->second, false)); 220 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)); 221 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 222 } 223 224 if (!Ctors.empty()) { 225 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 226 new llvm::GlobalVariable(TheModule, AT, false, 227 llvm::GlobalValue::AppendingLinkage, 228 llvm::ConstantArray::get(AT, Ctors), 229 GlobalName); 230 } 231 } 232 233 void CodeGenModule::EmitAnnotations() { 234 if (Annotations.empty()) 235 return; 236 237 // Create a new global variable for the ConstantStruct in the Module. 238 llvm::Constant *Array = 239 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(), 240 Annotations.size()), 241 Annotations); 242 llvm::GlobalValue *gv = 243 new llvm::GlobalVariable(TheModule, Array->getType(), false, 244 llvm::GlobalValue::AppendingLinkage, Array, 245 "llvm.global.annotations"); 246 gv->setSection("llvm.metadata"); 247 } 248 249 static CodeGenModule::GVALinkage 250 GetLinkageForFunction(ASTContext &Context, const FunctionDecl *FD, 251 const LangOptions &Features) { 252 // Everything located semantically within an anonymous namespace is 253 // always internal. 254 if (FD->isInAnonymousNamespace()) 255 return CodeGenModule::GVA_Internal; 256 257 // "static" functions get internal linkage. 258 if (FD->getStorageClass() == FunctionDecl::Static && !isa<CXXMethodDecl>(FD)) 259 return CodeGenModule::GVA_Internal; 260 261 // The kind of external linkage this function will have, if it is not 262 // inline or static. 263 CodeGenModule::GVALinkage External = CodeGenModule::GVA_StrongExternal; 264 if (Context.getLangOptions().CPlusPlus && 265 FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 266 External = CodeGenModule::GVA_TemplateInstantiation; 267 268 if (!FD->isInlined()) 269 return External; 270 271 if (!Features.CPlusPlus || FD->hasAttr<GNUInlineAttr>()) { 272 // GNU or C99 inline semantics. Determine whether this symbol should be 273 // externally visible. 274 if (FD->isInlineDefinitionExternallyVisible()) 275 return External; 276 277 // C99 inline semantics, where the symbol is not externally visible. 278 return CodeGenModule::GVA_C99Inline; 279 } 280 281 // C++0x [temp.explicit]p9: 282 // [ Note: The intent is that an inline function that is the subject of 283 // an explicit instantiation declaration will still be implicitly 284 // instantiated when used so that the body can be considered for 285 // inlining, but that no out-of-line copy of the inline function would be 286 // generated in the translation unit. -- end note ] 287 if (FD->getTemplateSpecializationKind() 288 == TSK_ExplicitInstantiationDeclaration) 289 return CodeGenModule::GVA_C99Inline; 290 291 return CodeGenModule::GVA_CXXInline; 292 } 293 294 /// SetFunctionDefinitionAttributes - Set attributes for a global. 295 /// 296 /// FIXME: This is currently only done for aliases and functions, but not for 297 /// variables (these details are set in EmitGlobalVarDefinition for variables). 298 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D, 299 llvm::GlobalValue *GV) { 300 GVALinkage Linkage = GetLinkageForFunction(getContext(), D, Features); 301 302 if (Linkage == GVA_Internal) { 303 GV->setLinkage(llvm::Function::InternalLinkage); 304 } else if (D->hasAttr<DLLExportAttr>()) { 305 GV->setLinkage(llvm::Function::DLLExportLinkage); 306 } else if (D->hasAttr<WeakAttr>()) { 307 GV->setLinkage(llvm::Function::WeakAnyLinkage); 308 } else if (Linkage == GVA_C99Inline) { 309 // In C99 mode, 'inline' functions are guaranteed to have a strong 310 // definition somewhere else, so we can use available_externally linkage. 311 GV->setLinkage(llvm::Function::AvailableExternallyLinkage); 312 } else if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) { 313 // In C++, the compiler has to emit a definition in every translation unit 314 // that references the function. We should use linkonce_odr because 315 // a) if all references in this translation unit are optimized away, we 316 // don't need to codegen it. b) if the function persists, it needs to be 317 // merged with other definitions. c) C++ has the ODR, so we know the 318 // definition is dependable. 319 GV->setLinkage(llvm::Function::LinkOnceODRLinkage); 320 } else { 321 assert(Linkage == GVA_StrongExternal); 322 // Otherwise, we have strong external linkage. 323 GV->setLinkage(llvm::Function::ExternalLinkage); 324 } 325 326 SetCommonAttributes(D, GV); 327 } 328 329 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 330 const CGFunctionInfo &Info, 331 llvm::Function *F) { 332 unsigned CallingConv; 333 AttributeListType AttributeList; 334 ConstructAttributeList(Info, D, AttributeList, CallingConv); 335 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(), 336 AttributeList.size())); 337 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 338 } 339 340 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 341 llvm::Function *F) { 342 if (!Features.Exceptions && !Features.ObjCNonFragileABI) 343 F->addFnAttr(llvm::Attribute::NoUnwind); 344 345 if (D->hasAttr<AlwaysInlineAttr>()) 346 F->addFnAttr(llvm::Attribute::AlwaysInline); 347 348 if (D->hasAttr<NoInlineAttr>()) 349 F->addFnAttr(llvm::Attribute::NoInline); 350 351 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) 352 F->setAlignment(AA->getAlignment()/8); 353 // C++ ABI requires 2-byte alignment for member functions. 354 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 355 F->setAlignment(2); 356 } 357 358 void CodeGenModule::SetCommonAttributes(const Decl *D, 359 llvm::GlobalValue *GV) { 360 setGlobalVisibility(GV, D); 361 362 if (D->hasAttr<UsedAttr>()) 363 AddUsedGlobal(GV); 364 365 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 366 GV->setSection(SA->getName()); 367 } 368 369 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 370 llvm::Function *F, 371 const CGFunctionInfo &FI) { 372 SetLLVMFunctionAttributes(D, FI, F); 373 SetLLVMFunctionAttributesForDefinition(D, F); 374 375 F->setLinkage(llvm::Function::InternalLinkage); 376 377 SetCommonAttributes(D, F); 378 } 379 380 void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD, 381 llvm::Function *F, 382 bool IsIncompleteFunction) { 383 if (!IsIncompleteFunction) 384 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F); 385 386 // Only a few attributes are set on declarations; these may later be 387 // overridden by a definition. 388 389 if (FD->hasAttr<DLLImportAttr>()) { 390 F->setLinkage(llvm::Function::DLLImportLinkage); 391 } else if (FD->hasAttr<WeakAttr>() || 392 FD->hasAttr<WeakImportAttr>()) { 393 // "extern_weak" is overloaded in LLVM; we probably should have 394 // separate linkage types for this. 395 F->setLinkage(llvm::Function::ExternalWeakLinkage); 396 } else { 397 F->setLinkage(llvm::Function::ExternalLinkage); 398 } 399 400 if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 401 F->setSection(SA->getName()); 402 } 403 404 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) { 405 assert(!GV->isDeclaration() && 406 "Only globals with definition can force usage."); 407 LLVMUsed.push_back(GV); 408 } 409 410 void CodeGenModule::EmitLLVMUsed() { 411 // Don't create llvm.used if there is no need. 412 if (LLVMUsed.empty()) 413 return; 414 415 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext); 416 417 // Convert LLVMUsed to what ConstantArray needs. 418 std::vector<llvm::Constant*> UsedArray; 419 UsedArray.resize(LLVMUsed.size()); 420 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) { 421 UsedArray[i] = 422 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), 423 i8PTy); 424 } 425 426 if (UsedArray.empty()) 427 return; 428 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size()); 429 430 llvm::GlobalVariable *GV = 431 new llvm::GlobalVariable(getModule(), ATy, false, 432 llvm::GlobalValue::AppendingLinkage, 433 llvm::ConstantArray::get(ATy, UsedArray), 434 "llvm.used"); 435 436 GV->setSection("llvm.metadata"); 437 } 438 439 void CodeGenModule::EmitDeferred() { 440 // Emit code for any potentially referenced deferred decls. Since a 441 // previously unused static decl may become used during the generation of code 442 // for a static function, iterate until no changes are made. 443 while (!DeferredDeclsToEmit.empty()) { 444 GlobalDecl D = DeferredDeclsToEmit.back(); 445 DeferredDeclsToEmit.pop_back(); 446 447 // The mangled name for the decl must have been emitted in GlobalDeclMap. 448 // Look it up to see if it was defined with a stronger definition (e.g. an 449 // extern inline function with a strong function redefinition). If so, 450 // just ignore the deferred decl. 451 llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)]; 452 assert(CGRef && "Deferred decl wasn't referenced?"); 453 454 if (!CGRef->isDeclaration()) 455 continue; 456 457 // Otherwise, emit the definition and move on to the next one. 458 EmitGlobalDefinition(D); 459 } 460 } 461 462 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the 463 /// annotation information for a given GlobalValue. The annotation struct is 464 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 465 /// GlobalValue being annotated. The second field is the constant string 466 /// created from the AnnotateAttr's annotation. The third field is a constant 467 /// string containing the name of the translation unit. The fourth field is 468 /// the line number in the file of the annotated value declaration. 469 /// 470 /// FIXME: this does not unique the annotation string constants, as llvm-gcc 471 /// appears to. 472 /// 473 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 474 const AnnotateAttr *AA, 475 unsigned LineNo) { 476 llvm::Module *M = &getModule(); 477 478 // get [N x i8] constants for the annotation string, and the filename string 479 // which are the 2nd and 3rd elements of the global annotation structure. 480 const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext); 481 llvm::Constant *anno = llvm::ConstantArray::get(VMContext, 482 AA->getAnnotation(), true); 483 llvm::Constant *unit = llvm::ConstantArray::get(VMContext, 484 M->getModuleIdentifier(), 485 true); 486 487 // Get the two global values corresponding to the ConstantArrays we just 488 // created to hold the bytes of the strings. 489 llvm::GlobalValue *annoGV = 490 new llvm::GlobalVariable(*M, anno->getType(), false, 491 llvm::GlobalValue::PrivateLinkage, anno, 492 GV->getName()); 493 // translation unit name string, emitted into the llvm.metadata section. 494 llvm::GlobalValue *unitGV = 495 new llvm::GlobalVariable(*M, unit->getType(), false, 496 llvm::GlobalValue::PrivateLinkage, unit, 497 ".str"); 498 499 // Create the ConstantStruct for the global annotation. 500 llvm::Constant *Fields[4] = { 501 llvm::ConstantExpr::getBitCast(GV, SBP), 502 llvm::ConstantExpr::getBitCast(annoGV, SBP), 503 llvm::ConstantExpr::getBitCast(unitGV, SBP), 504 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo) 505 }; 506 return llvm::ConstantStruct::get(VMContext, Fields, 4, false); 507 } 508 509 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 510 // Never defer when EmitAllDecls is specified or the decl has 511 // attribute used. 512 if (Features.EmitAllDecls || Global->hasAttr<UsedAttr>()) 513 return false; 514 515 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 516 // Constructors and destructors should never be deferred. 517 if (FD->hasAttr<ConstructorAttr>() || 518 FD->hasAttr<DestructorAttr>()) 519 return false; 520 521 GVALinkage Linkage = GetLinkageForFunction(getContext(), FD, Features); 522 523 // static, static inline, always_inline, and extern inline functions can 524 // always be deferred. Normal inline functions can be deferred in C99/C++. 525 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline || 526 Linkage == GVA_CXXInline) 527 return true; 528 return false; 529 } 530 531 const VarDecl *VD = cast<VarDecl>(Global); 532 assert(VD->isFileVarDecl() && "Invalid decl"); 533 534 // We never want to defer structs that have non-trivial constructors or 535 // destructors. 536 537 // FIXME: Handle references. 538 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) { 539 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 540 if (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()) 541 return false; 542 } 543 } 544 545 // Static data may be deferred, but out-of-line static data members 546 // cannot be. 547 if (VD->isInAnonymousNamespace()) 548 return true; 549 if (VD->getStorageClass() == VarDecl::Static) { 550 // Initializer has side effects? 551 if (VD->getInit() && VD->getInit()->HasSideEffects(Context)) 552 return false; 553 return !(VD->isStaticDataMember() && VD->isOutOfLine()); 554 } 555 return false; 556 } 557 558 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 559 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl()); 560 561 // If this is an alias definition (which otherwise looks like a declaration) 562 // emit it now. 563 if (Global->hasAttr<AliasAttr>()) 564 return EmitAliasDefinition(Global); 565 566 // Ignore declarations, they will be emitted on their first use. 567 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 568 // Forward declarations are emitted lazily on first use. 569 if (!FD->isThisDeclarationADefinition()) 570 return; 571 } else { 572 const VarDecl *VD = cast<VarDecl>(Global); 573 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 574 575 // In C++, if this is marked "extern", defer code generation. 576 if (getLangOptions().CPlusPlus && !VD->getInit() && 577 (VD->getStorageClass() == VarDecl::Extern || 578 VD->isExternC())) 579 return; 580 581 // In C, if this isn't a definition, defer code generation. 582 if (!getLangOptions().CPlusPlus && !VD->getInit()) 583 return; 584 } 585 586 // Defer code generation when possible if this is a static definition, inline 587 // function etc. These we only want to emit if they are used. 588 if (MayDeferGeneration(Global)) { 589 // If the value has already been used, add it directly to the 590 // DeferredDeclsToEmit list. 591 const char *MangledName = getMangledName(GD); 592 if (GlobalDeclMap.count(MangledName)) 593 DeferredDeclsToEmit.push_back(GD); 594 else { 595 // Otherwise, remember that we saw a deferred decl with this name. The 596 // first use of the mangled name will cause it to move into 597 // DeferredDeclsToEmit. 598 DeferredDecls[MangledName] = GD; 599 } 600 return; 601 } 602 603 // Otherwise emit the definition. 604 EmitGlobalDefinition(GD); 605 } 606 607 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) { 608 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 609 610 PrettyStackTraceDecl CrashInfo((ValueDecl *)D, D->getLocation(), 611 Context.getSourceManager(), 612 "Generating code for declaration"); 613 614 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 615 EmitCXXConstructor(CD, GD.getCtorType()); 616 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) 617 EmitCXXDestructor(DD, GD.getDtorType()); 618 else if (isa<FunctionDecl>(D)) 619 EmitGlobalFunctionDefinition(GD); 620 else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 621 EmitGlobalVarDefinition(VD); 622 else { 623 assert(0 && "Invalid argument to EmitGlobalDefinition()"); 624 } 625 } 626 627 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 628 /// module, create and return an llvm Function with the specified type. If there 629 /// is something in the module with the specified name, return it potentially 630 /// bitcasted to the right type. 631 /// 632 /// If D is non-null, it specifies a decl that correspond to this. This is used 633 /// to set the attributes on the function when it is first created. 634 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName, 635 const llvm::Type *Ty, 636 GlobalDecl D) { 637 // Lookup the entry, lazily creating it if necessary. 638 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName]; 639 if (Entry) { 640 if (Entry->getType()->getElementType() == Ty) 641 return Entry; 642 643 // Make sure the result is of the correct type. 644 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 645 return llvm::ConstantExpr::getBitCast(Entry, PTy); 646 } 647 648 // This is the first use or definition of a mangled name. If there is a 649 // deferred decl with this name, remember that we need to emit it at the end 650 // of the file. 651 llvm::DenseMap<const char*, GlobalDecl>::iterator DDI = 652 DeferredDecls.find(MangledName); 653 if (DDI != DeferredDecls.end()) { 654 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 655 // list, and remove it from DeferredDecls (since we don't need it anymore). 656 DeferredDeclsToEmit.push_back(DDI->second); 657 DeferredDecls.erase(DDI); 658 } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) { 659 // If this the first reference to a C++ inline function in a class, queue up 660 // the deferred function body for emission. These are not seen as 661 // top-level declarations. 662 if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD)) 663 DeferredDeclsToEmit.push_back(D); 664 // A called constructor which has no definition or declaration need be 665 // synthesized. 666 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 667 const CXXRecordDecl *ClassDecl = 668 cast<CXXRecordDecl>(CD->getDeclContext()); 669 if (CD->isCopyConstructor(getContext())) 670 DeferredCopyConstructorToEmit(D); 671 else if (!ClassDecl->hasUserDeclaredConstructor()) 672 DeferredDeclsToEmit.push_back(D); 673 } 674 else if (isa<CXXDestructorDecl>(FD)) 675 DeferredDestructorToEmit(D); 676 else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 677 if (MD->isCopyAssignment()) 678 DeferredCopyAssignmentToEmit(D); 679 } 680 681 // This function doesn't have a complete type (for example, the return 682 // type is an incomplete struct). Use a fake type instead, and make 683 // sure not to try to set attributes. 684 bool IsIncompleteFunction = false; 685 if (!isa<llvm::FunctionType>(Ty)) { 686 Ty = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), 687 std::vector<const llvm::Type*>(), false); 688 IsIncompleteFunction = true; 689 } 690 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty), 691 llvm::Function::ExternalLinkage, 692 "", &getModule()); 693 F->setName(MangledName); 694 if (D.getDecl()) 695 SetFunctionAttributes(cast<FunctionDecl>(D.getDecl()), F, 696 IsIncompleteFunction); 697 Entry = F; 698 return F; 699 } 700 701 /// Defer definition of copy constructor(s) which need be implicitly defined. 702 void CodeGenModule::DeferredCopyConstructorToEmit(GlobalDecl CopyCtorDecl) { 703 const CXXConstructorDecl *CD = 704 cast<CXXConstructorDecl>(CopyCtorDecl.getDecl()); 705 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext()); 706 if (ClassDecl->hasTrivialCopyConstructor() || 707 ClassDecl->hasUserDeclaredCopyConstructor()) 708 return; 709 710 // First make sure all direct base classes and virtual bases and non-static 711 // data mebers which need to have their copy constructors implicitly defined 712 // are defined. 12.8.p7 713 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); 714 Base != ClassDecl->bases_end(); ++Base) { 715 CXXRecordDecl *BaseClassDecl 716 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 717 if (CXXConstructorDecl *BaseCopyCtor = 718 BaseClassDecl->getCopyConstructor(Context, 0)) 719 GetAddrOfCXXConstructor(BaseCopyCtor, Ctor_Complete); 720 } 721 722 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 723 FieldEnd = ClassDecl->field_end(); 724 Field != FieldEnd; ++Field) { 725 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 726 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 727 FieldType = Array->getElementType(); 728 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 729 if ((*Field)->isAnonymousStructOrUnion()) 730 continue; 731 CXXRecordDecl *FieldClassDecl 732 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 733 if (CXXConstructorDecl *FieldCopyCtor = 734 FieldClassDecl->getCopyConstructor(Context, 0)) 735 GetAddrOfCXXConstructor(FieldCopyCtor, Ctor_Complete); 736 } 737 } 738 DeferredDeclsToEmit.push_back(CopyCtorDecl); 739 } 740 741 /// Defer definition of copy assignments which need be implicitly defined. 742 void CodeGenModule::DeferredCopyAssignmentToEmit(GlobalDecl CopyAssignDecl) { 743 const CXXMethodDecl *CD = cast<CXXMethodDecl>(CopyAssignDecl.getDecl()); 744 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext()); 745 746 if (ClassDecl->hasTrivialCopyAssignment() || 747 ClassDecl->hasUserDeclaredCopyAssignment()) 748 return; 749 750 // First make sure all direct base classes and virtual bases and non-static 751 // data mebers which need to have their copy assignments implicitly defined 752 // are defined. 12.8.p12 753 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); 754 Base != ClassDecl->bases_end(); ++Base) { 755 CXXRecordDecl *BaseClassDecl 756 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 757 const CXXMethodDecl *MD = 0; 758 if (!BaseClassDecl->hasTrivialCopyAssignment() && 759 !BaseClassDecl->hasUserDeclaredCopyAssignment() && 760 BaseClassDecl->hasConstCopyAssignment(getContext(), MD)) 761 GetAddrOfFunction(MD, 0); 762 } 763 764 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 765 FieldEnd = ClassDecl->field_end(); 766 Field != FieldEnd; ++Field) { 767 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 768 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 769 FieldType = Array->getElementType(); 770 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 771 if ((*Field)->isAnonymousStructOrUnion()) 772 continue; 773 CXXRecordDecl *FieldClassDecl 774 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 775 const CXXMethodDecl *MD = 0; 776 if (!FieldClassDecl->hasTrivialCopyAssignment() && 777 !FieldClassDecl->hasUserDeclaredCopyAssignment() && 778 FieldClassDecl->hasConstCopyAssignment(getContext(), MD)) 779 GetAddrOfFunction(MD, 0); 780 } 781 } 782 DeferredDeclsToEmit.push_back(CopyAssignDecl); 783 } 784 785 void CodeGenModule::DeferredDestructorToEmit(GlobalDecl DtorDecl) { 786 const CXXDestructorDecl *DD = cast<CXXDestructorDecl>(DtorDecl.getDecl()); 787 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext()); 788 if (ClassDecl->hasTrivialDestructor() || 789 ClassDecl->hasUserDeclaredDestructor()) 790 return; 791 792 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); 793 Base != ClassDecl->bases_end(); ++Base) { 794 CXXRecordDecl *BaseClassDecl 795 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 796 if (const CXXDestructorDecl *BaseDtor = 797 BaseClassDecl->getDestructor(Context)) 798 GetAddrOfCXXDestructor(BaseDtor, Dtor_Complete); 799 } 800 801 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 802 FieldEnd = ClassDecl->field_end(); 803 Field != FieldEnd; ++Field) { 804 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 805 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 806 FieldType = Array->getElementType(); 807 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 808 if ((*Field)->isAnonymousStructOrUnion()) 809 continue; 810 CXXRecordDecl *FieldClassDecl 811 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 812 if (const CXXDestructorDecl *FieldDtor = 813 FieldClassDecl->getDestructor(Context)) 814 GetAddrOfCXXDestructor(FieldDtor, Dtor_Complete); 815 } 816 } 817 DeferredDeclsToEmit.push_back(DtorDecl); 818 } 819 820 821 /// GetAddrOfFunction - Return the address of the given function. If Ty is 822 /// non-null, then this function will use the specified type if it has to 823 /// create it (this occurs when we see a definition of the function). 824 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 825 const llvm::Type *Ty) { 826 // If there was no specific requested type, just convert it now. 827 if (!Ty) 828 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 829 return GetOrCreateLLVMFunction(getMangledName(GD), Ty, GD); 830 } 831 832 /// CreateRuntimeFunction - Create a new runtime function with the specified 833 /// type and name. 834 llvm::Constant * 835 CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy, 836 const char *Name) { 837 // Convert Name to be a uniqued string from the IdentifierInfo table. 838 Name = getContext().Idents.get(Name).getNameStart(); 839 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl()); 840 } 841 842 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 843 /// create and return an llvm GlobalVariable with the specified type. If there 844 /// is something in the module with the specified name, return it potentially 845 /// bitcasted to the right type. 846 /// 847 /// If D is non-null, it specifies a decl that correspond to this. This is used 848 /// to set the attributes on the global when it is first created. 849 llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName, 850 const llvm::PointerType*Ty, 851 const VarDecl *D) { 852 // Lookup the entry, lazily creating it if necessary. 853 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName]; 854 if (Entry) { 855 if (Entry->getType() == Ty) 856 return Entry; 857 858 // Make sure the result is of the correct type. 859 return llvm::ConstantExpr::getBitCast(Entry, Ty); 860 } 861 862 // This is the first use or definition of a mangled name. If there is a 863 // deferred decl with this name, remember that we need to emit it at the end 864 // of the file. 865 llvm::DenseMap<const char*, GlobalDecl>::iterator DDI = 866 DeferredDecls.find(MangledName); 867 if (DDI != DeferredDecls.end()) { 868 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 869 // list, and remove it from DeferredDecls (since we don't need it anymore). 870 DeferredDeclsToEmit.push_back(DDI->second); 871 DeferredDecls.erase(DDI); 872 } 873 874 llvm::GlobalVariable *GV = 875 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false, 876 llvm::GlobalValue::ExternalLinkage, 877 0, "", 0, 878 false, Ty->getAddressSpace()); 879 GV->setName(MangledName); 880 881 // Handle things which are present even on external declarations. 882 if (D) { 883 // FIXME: This code is overly simple and should be merged with other global 884 // handling. 885 GV->setConstant(D->getType().isConstant(Context)); 886 887 // FIXME: Merge with other attribute handling code. 888 if (D->getStorageClass() == VarDecl::PrivateExtern) 889 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 890 891 if (D->hasAttr<WeakAttr>() || 892 D->hasAttr<WeakImportAttr>()) 893 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 894 895 GV->setThreadLocal(D->isThreadSpecified()); 896 } 897 898 return Entry = GV; 899 } 900 901 902 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 903 /// given global variable. If Ty is non-null and if the global doesn't exist, 904 /// then it will be greated with the specified type instead of whatever the 905 /// normal requested type would be. 906 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 907 const llvm::Type *Ty) { 908 assert(D->hasGlobalStorage() && "Not a global variable"); 909 QualType ASTTy = D->getType(); 910 if (Ty == 0) 911 Ty = getTypes().ConvertTypeForMem(ASTTy); 912 913 const llvm::PointerType *PTy = 914 llvm::PointerType::get(Ty, ASTTy.getAddressSpace()); 915 return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D); 916 } 917 918 /// CreateRuntimeVariable - Create a new runtime global variable with the 919 /// specified type and name. 920 llvm::Constant * 921 CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty, 922 const char *Name) { 923 // Convert Name to be a uniqued string from the IdentifierInfo table. 924 Name = getContext().Idents.get(Name).getNameStart(); 925 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0); 926 } 927 928 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 929 assert(!D->getInit() && "Cannot emit definite definitions here!"); 930 931 if (MayDeferGeneration(D)) { 932 // If we have not seen a reference to this variable yet, place it 933 // into the deferred declarations table to be emitted if needed 934 // later. 935 const char *MangledName = getMangledName(D); 936 if (GlobalDeclMap.count(MangledName) == 0) { 937 DeferredDecls[MangledName] = D; 938 return; 939 } 940 } 941 942 // The tentative definition is the only definition. 943 EmitGlobalVarDefinition(D); 944 } 945 946 static CodeGenModule::GVALinkage 947 GetLinkageForVariable(ASTContext &Context, const VarDecl *VD) { 948 // Everything located semantically within an anonymous namespace is 949 // always internal. 950 if (VD->isInAnonymousNamespace()) 951 return CodeGenModule::GVA_Internal; 952 953 // Handle linkage for static data members. 954 if (VD->isStaticDataMember()) { 955 switch (VD->getTemplateSpecializationKind()) { 956 case TSK_Undeclared: 957 case TSK_ExplicitSpecialization: 958 case TSK_ExplicitInstantiationDefinition: 959 return CodeGenModule::GVA_StrongExternal; 960 961 case TSK_ExplicitInstantiationDeclaration: 962 llvm::llvm_unreachable("Variable should not be instantiated"); 963 // Fall through to treat this like any other instantiation. 964 965 case TSK_ImplicitInstantiation: 966 return CodeGenModule::GVA_TemplateInstantiation; 967 } 968 } 969 970 // Static variables get internal linkage. 971 if (VD->getStorageClass() == VarDecl::Static) 972 return CodeGenModule::GVA_Internal; 973 974 return CodeGenModule::GVA_StrongExternal; 975 } 976 977 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 978 llvm::Constant *Init = 0; 979 QualType ASTTy = D->getType(); 980 981 if (D->getInit() == 0) { 982 // This is a tentative definition; tentative definitions are 983 // implicitly initialized with { 0 }. 984 // 985 // Note that tentative definitions are only emitted at the end of 986 // a translation unit, so they should never have incomplete 987 // type. In addition, EmitTentativeDefinition makes sure that we 988 // never attempt to emit a tentative definition if a real one 989 // exists. A use may still exists, however, so we still may need 990 // to do a RAUW. 991 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 992 Init = EmitNullConstant(D->getType()); 993 } else { 994 Init = EmitConstantExpr(D->getInit(), D->getType()); 995 996 if (!Init) { 997 QualType T = D->getInit()->getType(); 998 if (getLangOptions().CPlusPlus) { 999 CXXGlobalInits.push_back(D); 1000 Init = EmitNullConstant(T); 1001 } else { 1002 ErrorUnsupported(D, "static initializer"); 1003 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 1004 } 1005 } 1006 } 1007 1008 const llvm::Type* InitType = Init->getType(); 1009 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 1010 1011 // Strip off a bitcast if we got one back. 1012 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1013 assert(CE->getOpcode() == llvm::Instruction::BitCast || 1014 // all zero index gep. 1015 CE->getOpcode() == llvm::Instruction::GetElementPtr); 1016 Entry = CE->getOperand(0); 1017 } 1018 1019 // Entry is now either a Function or GlobalVariable. 1020 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 1021 1022 // We have a definition after a declaration with the wrong type. 1023 // We must make a new GlobalVariable* and update everything that used OldGV 1024 // (a declaration or tentative definition) with the new GlobalVariable* 1025 // (which will be a definition). 1026 // 1027 // This happens if there is a prototype for a global (e.g. 1028 // "extern int x[];") and then a definition of a different type (e.g. 1029 // "int x[10];"). This also happens when an initializer has a different type 1030 // from the type of the global (this happens with unions). 1031 if (GV == 0 || 1032 GV->getType()->getElementType() != InitType || 1033 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) { 1034 1035 // Remove the old entry from GlobalDeclMap so that we'll create a new one. 1036 GlobalDeclMap.erase(getMangledName(D)); 1037 1038 // Make a new global with the correct type, this is now guaranteed to work. 1039 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 1040 GV->takeName(cast<llvm::GlobalValue>(Entry)); 1041 1042 // Replace all uses of the old global with the new global 1043 llvm::Constant *NewPtrForOldDecl = 1044 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 1045 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1046 1047 // Erase the old global, since it is no longer used. 1048 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 1049 } 1050 1051 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) { 1052 SourceManager &SM = Context.getSourceManager(); 1053 AddAnnotation(EmitAnnotateAttr(GV, AA, 1054 SM.getInstantiationLineNumber(D->getLocation()))); 1055 } 1056 1057 GV->setInitializer(Init); 1058 1059 // If it is safe to mark the global 'constant', do so now. 1060 GV->setConstant(false); 1061 if (D->getType().isConstant(Context)) { 1062 // FIXME: In C++, if the variable has a non-trivial ctor/dtor or any mutable 1063 // members, it cannot be declared "LLVM const". 1064 GV->setConstant(true); 1065 } 1066 1067 GV->setAlignment(getContext().getDeclAlignInBytes(D)); 1068 1069 // Set the llvm linkage type as appropriate. 1070 GVALinkage Linkage = GetLinkageForVariable(getContext(), D); 1071 if (Linkage == GVA_Internal) 1072 GV->setLinkage(llvm::Function::InternalLinkage); 1073 else if (D->hasAttr<DLLImportAttr>()) 1074 GV->setLinkage(llvm::Function::DLLImportLinkage); 1075 else if (D->hasAttr<DLLExportAttr>()) 1076 GV->setLinkage(llvm::Function::DLLExportLinkage); 1077 else if (D->hasAttr<WeakAttr>()) { 1078 if (GV->isConstant()) 1079 GV->setLinkage(llvm::GlobalVariable::WeakODRLinkage); 1080 else 1081 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 1082 } else if (Linkage == GVA_TemplateInstantiation) 1083 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 1084 else if (!CompileOpts.NoCommon && 1085 !D->hasExternalStorage() && !D->getInit() && 1086 !D->getAttr<SectionAttr>()) { 1087 GV->setLinkage(llvm::GlobalVariable::CommonLinkage); 1088 // common vars aren't constant even if declared const. 1089 GV->setConstant(false); 1090 } else 1091 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage); 1092 1093 SetCommonAttributes(D, GV); 1094 1095 // Emit global variable debug information. 1096 if (CGDebugInfo *DI = getDebugInfo()) { 1097 DI->setLocation(D->getLocation()); 1098 DI->EmitGlobalVariable(GV, D); 1099 } 1100 } 1101 1102 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 1103 /// implement a function with no prototype, e.g. "int foo() {}". If there are 1104 /// existing call uses of the old function in the module, this adjusts them to 1105 /// call the new function directly. 1106 /// 1107 /// This is not just a cleanup: the always_inline pass requires direct calls to 1108 /// functions to be able to inline them. If there is a bitcast in the way, it 1109 /// won't inline them. Instcombine normally deletes these calls, but it isn't 1110 /// run at -O0. 1111 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 1112 llvm::Function *NewFn) { 1113 // If we're redefining a global as a function, don't transform it. 1114 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old); 1115 if (OldFn == 0) return; 1116 1117 const llvm::Type *NewRetTy = NewFn->getReturnType(); 1118 llvm::SmallVector<llvm::Value*, 4> ArgList; 1119 1120 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end(); 1121 UI != E; ) { 1122 // TODO: Do invokes ever occur in C code? If so, we should handle them too. 1123 unsigned OpNo = UI.getOperandNo(); 1124 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*UI++); 1125 if (!CI || OpNo != 0) continue; 1126 1127 // If the return types don't match exactly, and if the call isn't dead, then 1128 // we can't transform this call. 1129 if (CI->getType() != NewRetTy && !CI->use_empty()) 1130 continue; 1131 1132 // If the function was passed too few arguments, don't transform. If extra 1133 // arguments were passed, we silently drop them. If any of the types 1134 // mismatch, we don't transform. 1135 unsigned ArgNo = 0; 1136 bool DontTransform = false; 1137 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(), 1138 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) { 1139 if (CI->getNumOperands()-1 == ArgNo || 1140 CI->getOperand(ArgNo+1)->getType() != AI->getType()) { 1141 DontTransform = true; 1142 break; 1143 } 1144 } 1145 if (DontTransform) 1146 continue; 1147 1148 // Okay, we can transform this. Create the new call instruction and copy 1149 // over the required information. 1150 ArgList.append(CI->op_begin()+1, CI->op_begin()+1+ArgNo); 1151 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(), 1152 ArgList.end(), "", CI); 1153 ArgList.clear(); 1154 if (!NewCall->getType()->isVoidTy()) 1155 NewCall->takeName(CI); 1156 NewCall->setAttributes(CI->getAttributes()); 1157 NewCall->setCallingConv(CI->getCallingConv()); 1158 1159 // Finally, remove the old call, replacing any uses with the new one. 1160 if (!CI->use_empty()) 1161 CI->replaceAllUsesWith(NewCall); 1162 1163 // Copy any custom metadata attached with CI. 1164 llvm::MetadataContext &TheMetadata = CI->getContext().getMetadata(); 1165 TheMetadata.copyMD(CI, NewCall); 1166 1167 CI->eraseFromParent(); 1168 } 1169 } 1170 1171 1172 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { 1173 const llvm::FunctionType *Ty; 1174 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 1175 1176 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 1177 bool isVariadic = D->getType()->getAs<FunctionProtoType>()->isVariadic(); 1178 1179 Ty = getTypes().GetFunctionType(getTypes().getFunctionInfo(MD), isVariadic); 1180 } else { 1181 Ty = cast<llvm::FunctionType>(getTypes().ConvertType(D->getType())); 1182 1183 // As a special case, make sure that definitions of K&R function 1184 // "type foo()" aren't declared as varargs (which forces the backend 1185 // to do unnecessary work). 1186 if (D->getType()->isFunctionNoProtoType()) { 1187 assert(Ty->isVarArg() && "Didn't lower type as expected"); 1188 // Due to stret, the lowered function could have arguments. 1189 // Just create the same type as was lowered by ConvertType 1190 // but strip off the varargs bit. 1191 std::vector<const llvm::Type*> Args(Ty->param_begin(), Ty->param_end()); 1192 Ty = llvm::FunctionType::get(Ty->getReturnType(), Args, false); 1193 } 1194 } 1195 1196 // Get or create the prototype for the function. 1197 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty); 1198 1199 // Strip off a bitcast if we got one back. 1200 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1201 assert(CE->getOpcode() == llvm::Instruction::BitCast); 1202 Entry = CE->getOperand(0); 1203 } 1204 1205 1206 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 1207 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry); 1208 1209 // If the types mismatch then we have to rewrite the definition. 1210 assert(OldFn->isDeclaration() && 1211 "Shouldn't replace non-declaration"); 1212 1213 // F is the Function* for the one with the wrong type, we must make a new 1214 // Function* and update everything that used F (a declaration) with the new 1215 // Function* (which will be a definition). 1216 // 1217 // This happens if there is a prototype for a function 1218 // (e.g. "int f()") and then a definition of a different type 1219 // (e.g. "int f(int x)"). Start by making a new function of the 1220 // correct type, RAUW, then steal the name. 1221 GlobalDeclMap.erase(getMangledName(D)); 1222 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 1223 NewFn->takeName(OldFn); 1224 1225 // If this is an implementation of a function without a prototype, try to 1226 // replace any existing uses of the function (which may be calls) with uses 1227 // of the new function 1228 if (D->getType()->isFunctionNoProtoType()) { 1229 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); 1230 OldFn->removeDeadConstantUsers(); 1231 } 1232 1233 // Replace uses of F with the Function we will endow with a body. 1234 if (!Entry->use_empty()) { 1235 llvm::Constant *NewPtrForOldDecl = 1236 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 1237 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1238 } 1239 1240 // Ok, delete the old function now, which is dead. 1241 OldFn->eraseFromParent(); 1242 1243 Entry = NewFn; 1244 } 1245 1246 llvm::Function *Fn = cast<llvm::Function>(Entry); 1247 1248 CodeGenFunction(*this).GenerateCode(D, Fn); 1249 1250 SetFunctionDefinitionAttributes(D, Fn); 1251 SetLLVMFunctionAttributesForDefinition(D, Fn); 1252 1253 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 1254 AddGlobalCtor(Fn, CA->getPriority()); 1255 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 1256 AddGlobalDtor(Fn, DA->getPriority()); 1257 } 1258 1259 void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) { 1260 const AliasAttr *AA = D->getAttr<AliasAttr>(); 1261 assert(AA && "Not an alias?"); 1262 1263 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 1264 1265 // Unique the name through the identifier table. 1266 const char *AliaseeName = AA->getAliasee().c_str(); 1267 AliaseeName = getContext().Idents.get(AliaseeName).getNameStart(); 1268 1269 // Create a reference to the named value. This ensures that it is emitted 1270 // if a deferred decl. 1271 llvm::Constant *Aliasee; 1272 if (isa<llvm::FunctionType>(DeclTy)) 1273 Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, GlobalDecl()); 1274 else 1275 Aliasee = GetOrCreateLLVMGlobal(AliaseeName, 1276 llvm::PointerType::getUnqual(DeclTy), 0); 1277 1278 // Create the new alias itself, but don't set a name yet. 1279 llvm::GlobalValue *GA = 1280 new llvm::GlobalAlias(Aliasee->getType(), 1281 llvm::Function::ExternalLinkage, 1282 "", Aliasee, &getModule()); 1283 1284 // See if there is already something with the alias' name in the module. 1285 const char *MangledName = getMangledName(D); 1286 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName]; 1287 1288 if (Entry && !Entry->isDeclaration()) { 1289 // If there is a definition in the module, then it wins over the alias. 1290 // This is dubious, but allow it to be safe. Just ignore the alias. 1291 GA->eraseFromParent(); 1292 return; 1293 } 1294 1295 if (Entry) { 1296 // If there is a declaration in the module, then we had an extern followed 1297 // by the alias, as in: 1298 // extern int test6(); 1299 // ... 1300 // int test6() __attribute__((alias("test7"))); 1301 // 1302 // Remove it and replace uses of it with the alias. 1303 1304 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 1305 Entry->getType())); 1306 Entry->eraseFromParent(); 1307 } 1308 1309 // Now we know that there is no conflict, set the name. 1310 Entry = GA; 1311 GA->setName(MangledName); 1312 1313 // Set attributes which are particular to an alias; this is a 1314 // specialization of the attributes which may be set on a global 1315 // variable/function. 1316 if (D->hasAttr<DLLExportAttr>()) { 1317 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1318 // The dllexport attribute is ignored for undefined symbols. 1319 if (FD->getBody()) 1320 GA->setLinkage(llvm::Function::DLLExportLinkage); 1321 } else { 1322 GA->setLinkage(llvm::Function::DLLExportLinkage); 1323 } 1324 } else if (D->hasAttr<WeakAttr>() || 1325 D->hasAttr<WeakImportAttr>()) { 1326 GA->setLinkage(llvm::Function::WeakAnyLinkage); 1327 } 1328 1329 SetCommonAttributes(D, GA); 1330 } 1331 1332 /// getBuiltinLibFunction - Given a builtin id for a function like 1333 /// "__builtin_fabsf", return a Function* for "fabsf". 1334 llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD, 1335 unsigned BuiltinID) { 1336 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) || 1337 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) && 1338 "isn't a lib fn"); 1339 1340 // Get the name, skip over the __builtin_ prefix (if necessary). 1341 const char *Name = Context.BuiltinInfo.GetName(BuiltinID); 1342 if (Context.BuiltinInfo.isLibFunction(BuiltinID)) 1343 Name += 10; 1344 1345 // Get the type for the builtin. 1346 ASTContext::GetBuiltinTypeError Error; 1347 QualType Type = Context.GetBuiltinType(BuiltinID, Error); 1348 assert(Error == ASTContext::GE_None && "Can't get builtin type"); 1349 1350 const llvm::FunctionType *Ty = 1351 cast<llvm::FunctionType>(getTypes().ConvertType(Type)); 1352 1353 // Unique the name through the identifier table. 1354 Name = getContext().Idents.get(Name).getNameStart(); 1355 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD)); 1356 } 1357 1358 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys, 1359 unsigned NumTys) { 1360 return llvm::Intrinsic::getDeclaration(&getModule(), 1361 (llvm::Intrinsic::ID)IID, Tys, NumTys); 1362 } 1363 1364 llvm::Function *CodeGenModule::getMemCpyFn() { 1365 if (MemCpyFn) return MemCpyFn; 1366 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext); 1367 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1); 1368 } 1369 1370 llvm::Function *CodeGenModule::getMemMoveFn() { 1371 if (MemMoveFn) return MemMoveFn; 1372 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext); 1373 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1); 1374 } 1375 1376 llvm::Function *CodeGenModule::getMemSetFn() { 1377 if (MemSetFn) return MemSetFn; 1378 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext); 1379 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1); 1380 } 1381 1382 static llvm::StringMapEntry<llvm::Constant*> & 1383 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 1384 const StringLiteral *Literal, 1385 bool TargetIsLSB, 1386 bool &IsUTF16, 1387 unsigned &StringLength) { 1388 unsigned NumBytes = Literal->getByteLength(); 1389 1390 // Check for simple case. 1391 if (!Literal->containsNonAsciiOrNull()) { 1392 StringLength = NumBytes; 1393 return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(), 1394 StringLength)); 1395 } 1396 1397 // Otherwise, convert the UTF8 literals into a byte string. 1398 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes); 1399 const UTF8 *FromPtr = (UTF8 *)Literal->getStrData(); 1400 UTF16 *ToPtr = &ToBuf[0]; 1401 1402 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1403 &ToPtr, ToPtr + NumBytes, 1404 strictConversion); 1405 1406 // Check for conversion failure. 1407 if (Result != conversionOK) { 1408 // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string and remove 1409 // this duplicate code. 1410 assert(Result == sourceIllegal && "UTF-8 to UTF-16 conversion failed"); 1411 StringLength = NumBytes; 1412 return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(), 1413 StringLength)); 1414 } 1415 1416 // ConvertUTF8toUTF16 returns the length in ToPtr. 1417 StringLength = ToPtr - &ToBuf[0]; 1418 1419 // Render the UTF-16 string into a byte array and convert to the target byte 1420 // order. 1421 // 1422 // FIXME: This isn't something we should need to do here. 1423 llvm::SmallString<128> AsBytes; 1424 AsBytes.reserve(StringLength * 2); 1425 for (unsigned i = 0; i != StringLength; ++i) { 1426 unsigned short Val = ToBuf[i]; 1427 if (TargetIsLSB) { 1428 AsBytes.push_back(Val & 0xFF); 1429 AsBytes.push_back(Val >> 8); 1430 } else { 1431 AsBytes.push_back(Val >> 8); 1432 AsBytes.push_back(Val & 0xFF); 1433 } 1434 } 1435 // Append one extra null character, the second is automatically added by our 1436 // caller. 1437 AsBytes.push_back(0); 1438 1439 IsUTF16 = true; 1440 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size())); 1441 } 1442 1443 llvm::Constant * 1444 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 1445 unsigned StringLength = 0; 1446 bool isUTF16 = false; 1447 llvm::StringMapEntry<llvm::Constant*> &Entry = 1448 GetConstantCFStringEntry(CFConstantStringMap, Literal, 1449 getTargetData().isLittleEndian(), 1450 isUTF16, StringLength); 1451 1452 if (llvm::Constant *C = Entry.getValue()) 1453 return C; 1454 1455 llvm::Constant *Zero = 1456 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1457 llvm::Constant *Zeros[] = { Zero, Zero }; 1458 1459 // If we don't already have it, get __CFConstantStringClassReference. 1460 if (!CFConstantStringClassRef) { 1461 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1462 Ty = llvm::ArrayType::get(Ty, 0); 1463 llvm::Constant *GV = CreateRuntimeVariable(Ty, 1464 "__CFConstantStringClassReference"); 1465 // Decay array -> ptr 1466 CFConstantStringClassRef = 1467 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1468 } 1469 1470 QualType CFTy = getContext().getCFConstantStringType(); 1471 1472 const llvm::StructType *STy = 1473 cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 1474 1475 std::vector<llvm::Constant*> Fields(4); 1476 1477 // Class pointer. 1478 Fields[0] = CFConstantStringClassRef; 1479 1480 // Flags. 1481 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1482 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 1483 llvm::ConstantInt::get(Ty, 0x07C8); 1484 1485 // String pointer. 1486 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1487 1488 const char *Sect = 0; 1489 llvm::GlobalValue::LinkageTypes Linkage; 1490 bool isConstant; 1491 if (isUTF16) { 1492 Sect = getContext().Target.getUnicodeStringSection(); 1493 // FIXME: why do utf strings get "_" labels instead of "L" labels? 1494 Linkage = llvm::GlobalValue::InternalLinkage; 1495 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but 1496 // does make plain ascii ones writable. 1497 isConstant = true; 1498 } else { 1499 Linkage = llvm::GlobalValue::PrivateLinkage; 1500 isConstant = !Features.WritableStrings; 1501 } 1502 1503 llvm::GlobalVariable *GV = 1504 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 1505 ".str"); 1506 if (Sect) 1507 GV->setSection(Sect); 1508 if (isUTF16) { 1509 unsigned Align = getContext().getTypeAlign(getContext().ShortTy)/8; 1510 GV->setAlignment(Align); 1511 } 1512 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1513 1514 // String length. 1515 Ty = getTypes().ConvertType(getContext().LongTy); 1516 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 1517 1518 // The struct. 1519 C = llvm::ConstantStruct::get(STy, Fields); 1520 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 1521 llvm::GlobalVariable::PrivateLinkage, C, 1522 "_unnamed_cfstring_"); 1523 if (const char *Sect = getContext().Target.getCFStringSection()) 1524 GV->setSection(Sect); 1525 Entry.setValue(GV); 1526 1527 return GV; 1528 } 1529 1530 /// GetStringForStringLiteral - Return the appropriate bytes for a 1531 /// string literal, properly padded to match the literal type. 1532 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) { 1533 const char *StrData = E->getStrData(); 1534 unsigned Len = E->getByteLength(); 1535 1536 const ConstantArrayType *CAT = 1537 getContext().getAsConstantArrayType(E->getType()); 1538 assert(CAT && "String isn't pointer or array!"); 1539 1540 // Resize the string to the right size. 1541 std::string Str(StrData, StrData+Len); 1542 uint64_t RealLen = CAT->getSize().getZExtValue(); 1543 1544 if (E->isWide()) 1545 RealLen *= getContext().Target.getWCharWidth()/8; 1546 1547 Str.resize(RealLen, '\0'); 1548 1549 return Str; 1550 } 1551 1552 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 1553 /// constant array for the given string literal. 1554 llvm::Constant * 1555 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 1556 // FIXME: This can be more efficient. 1557 return GetAddrOfConstantString(GetStringForStringLiteral(S)); 1558 } 1559 1560 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 1561 /// array for the given ObjCEncodeExpr node. 1562 llvm::Constant * 1563 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 1564 std::string Str; 1565 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 1566 1567 return GetAddrOfConstantCString(Str); 1568 } 1569 1570 1571 /// GenerateWritableString -- Creates storage for a string literal. 1572 static llvm::Constant *GenerateStringLiteral(const std::string &str, 1573 bool constant, 1574 CodeGenModule &CGM, 1575 const char *GlobalName) { 1576 // Create Constant for this string literal. Don't add a '\0'. 1577 llvm::Constant *C = 1578 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false); 1579 1580 // Create a global variable for this string 1581 return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant, 1582 llvm::GlobalValue::PrivateLinkage, 1583 C, GlobalName); 1584 } 1585 1586 /// GetAddrOfConstantString - Returns a pointer to a character array 1587 /// containing the literal. This contents are exactly that of the 1588 /// given string, i.e. it will not be null terminated automatically; 1589 /// see GetAddrOfConstantCString. Note that whether the result is 1590 /// actually a pointer to an LLVM constant depends on 1591 /// Feature.WriteableStrings. 1592 /// 1593 /// The result has pointer to array type. 1594 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str, 1595 const char *GlobalName) { 1596 bool IsConstant = !Features.WritableStrings; 1597 1598 // Get the default prefix if a name wasn't specified. 1599 if (!GlobalName) 1600 GlobalName = ".str"; 1601 1602 // Don't share any string literals if strings aren't constant. 1603 if (!IsConstant) 1604 return GenerateStringLiteral(str, false, *this, GlobalName); 1605 1606 llvm::StringMapEntry<llvm::Constant *> &Entry = 1607 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 1608 1609 if (Entry.getValue()) 1610 return Entry.getValue(); 1611 1612 // Create a global variable for this. 1613 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName); 1614 Entry.setValue(C); 1615 return C; 1616 } 1617 1618 /// GetAddrOfConstantCString - Returns a pointer to a character 1619 /// array containing the literal and a terminating '\-' 1620 /// character. The result has pointer to array type. 1621 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str, 1622 const char *GlobalName){ 1623 return GetAddrOfConstantString(str + '\0', GlobalName); 1624 } 1625 1626 /// EmitObjCPropertyImplementations - Emit information for synthesized 1627 /// properties for an implementation. 1628 void CodeGenModule::EmitObjCPropertyImplementations(const 1629 ObjCImplementationDecl *D) { 1630 for (ObjCImplementationDecl::propimpl_iterator 1631 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) { 1632 ObjCPropertyImplDecl *PID = *i; 1633 1634 // Dynamic is just for type-checking. 1635 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 1636 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 1637 1638 // Determine which methods need to be implemented, some may have 1639 // been overridden. Note that ::isSynthesized is not the method 1640 // we want, that just indicates if the decl came from a 1641 // property. What we want to know is if the method is defined in 1642 // this implementation. 1643 if (!D->getInstanceMethod(PD->getGetterName())) 1644 CodeGenFunction(*this).GenerateObjCGetter( 1645 const_cast<ObjCImplementationDecl *>(D), PID); 1646 if (!PD->isReadOnly() && 1647 !D->getInstanceMethod(PD->getSetterName())) 1648 CodeGenFunction(*this).GenerateObjCSetter( 1649 const_cast<ObjCImplementationDecl *>(D), PID); 1650 } 1651 } 1652 } 1653 1654 /// EmitNamespace - Emit all declarations in a namespace. 1655 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 1656 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end(); 1657 I != E; ++I) 1658 EmitTopLevelDecl(*I); 1659 } 1660 1661 // EmitLinkageSpec - Emit all declarations in a linkage spec. 1662 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 1663 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 1664 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 1665 ErrorUnsupported(LSD, "linkage spec"); 1666 return; 1667 } 1668 1669 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end(); 1670 I != E; ++I) 1671 EmitTopLevelDecl(*I); 1672 } 1673 1674 /// EmitTopLevelDecl - Emit code for a single top level declaration. 1675 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 1676 // If an error has occurred, stop code generation, but continue 1677 // parsing and semantic analysis (to ensure all warnings and errors 1678 // are emitted). 1679 if (Diags.hasErrorOccurred()) 1680 return; 1681 1682 // Ignore dependent declarations. 1683 if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 1684 return; 1685 1686 switch (D->getKind()) { 1687 case Decl::CXXConversion: 1688 case Decl::CXXMethod: 1689 case Decl::Function: 1690 // Skip function templates 1691 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate()) 1692 return; 1693 1694 EmitGlobal(cast<FunctionDecl>(D)); 1695 break; 1696 1697 case Decl::Var: 1698 EmitGlobal(cast<VarDecl>(D)); 1699 break; 1700 1701 // C++ Decls 1702 case Decl::Namespace: 1703 EmitNamespace(cast<NamespaceDecl>(D)); 1704 break; 1705 // No code generation needed. 1706 case Decl::Using: 1707 case Decl::UsingDirective: 1708 case Decl::ClassTemplate: 1709 case Decl::FunctionTemplate: 1710 case Decl::NamespaceAlias: 1711 break; 1712 case Decl::CXXConstructor: 1713 EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 1714 break; 1715 case Decl::CXXDestructor: 1716 EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 1717 break; 1718 1719 case Decl::StaticAssert: 1720 // Nothing to do. 1721 break; 1722 1723 // Objective-C Decls 1724 1725 // Forward declarations, no (immediate) code generation. 1726 case Decl::ObjCClass: 1727 case Decl::ObjCForwardProtocol: 1728 case Decl::ObjCCategory: 1729 case Decl::ObjCInterface: 1730 break; 1731 1732 case Decl::ObjCProtocol: 1733 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D)); 1734 break; 1735 1736 case Decl::ObjCCategoryImpl: 1737 // Categories have properties but don't support synthesize so we 1738 // can ignore them here. 1739 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 1740 break; 1741 1742 case Decl::ObjCImplementation: { 1743 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 1744 EmitObjCPropertyImplementations(OMD); 1745 Runtime->GenerateClass(OMD); 1746 break; 1747 } 1748 case Decl::ObjCMethod: { 1749 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 1750 // If this is not a prototype, emit the body. 1751 if (OMD->getBody()) 1752 CodeGenFunction(*this).GenerateObjCMethod(OMD); 1753 break; 1754 } 1755 case Decl::ObjCCompatibleAlias: 1756 // compatibility-alias is a directive and has no code gen. 1757 break; 1758 1759 case Decl::LinkageSpec: 1760 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 1761 break; 1762 1763 case Decl::FileScopeAsm: { 1764 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 1765 std::string AsmString(AD->getAsmString()->getStrData(), 1766 AD->getAsmString()->getByteLength()); 1767 1768 const std::string &S = getModule().getModuleInlineAsm(); 1769 if (S.empty()) 1770 getModule().setModuleInlineAsm(AsmString); 1771 else 1772 getModule().setModuleInlineAsm(S + '\n' + AsmString); 1773 break; 1774 } 1775 1776 default: 1777 // Make sure we handled everything we should, every other kind is a 1778 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 1779 // function. Need to recode Decl::Kind to do that easily. 1780 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 1781 } 1782 } 1783