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