CodeGenModule.cpp revision ee760330a415635369556796a97afcfd6207f4dc
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/Diagnostic.h" 25#include "clang/Basic/SourceManager.h" 26#include "clang/Basic/TargetInfo.h" 27#include "llvm/CallingConv.h" 28#include "llvm/Module.h" 29#include "llvm/Intrinsics.h" 30#include "llvm/Target/TargetData.h" 31using namespace clang; 32using namespace CodeGen; 33 34 35CodeGenModule::CodeGenModule(ASTContext &C, const CompileOptions &compileOpts, 36 llvm::Module &M, const llvm::TargetData &TD, 37 Diagnostic &diags) 38 : BlockModule(C, M, TD, Types, *this), Context(C), 39 Features(C.getLangOptions()), CompileOpts(compileOpts), TheModule(M), 40 TheTargetData(TD), Diags(diags), Types(C, M, TD), Runtime(0), 41 MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0) { 42 43 if (!Features.ObjC1) 44 Runtime = 0; 45 else if (!Features.NeXTRuntime) 46 Runtime = CreateGNUObjCRuntime(*this); 47 else if (Features.ObjCNonFragileABI) 48 Runtime = CreateMacNonFragileABIObjCRuntime(*this); 49 else 50 Runtime = CreateMacObjCRuntime(*this); 51 52 // If debug info generation is enabled, create the CGDebugInfo object. 53 DebugInfo = CompileOpts.DebugInfo ? new CGDebugInfo(this) : 0; 54} 55 56CodeGenModule::~CodeGenModule() { 57 delete Runtime; 58 delete DebugInfo; 59} 60 61void CodeGenModule::Release() { 62 EmitDeferred(); 63 if (Runtime) 64 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction()) 65 AddGlobalCtor(ObjCInitFunction); 66 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 67 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 68 EmitAnnotations(); 69 EmitLLVMUsed(); 70} 71 72/// ErrorUnsupported - Print out an error that codegen doesn't support the 73/// specified stmt yet. 74void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type, 75 bool OmitOnError) { 76 if (OmitOnError && getDiags().hasErrorOccurred()) 77 return; 78 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 79 "cannot compile this %0 yet"); 80 std::string Msg = Type; 81 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 82 << Msg << S->getSourceRange(); 83} 84 85/// ErrorUnsupported - Print out an error that codegen doesn't support the 86/// specified decl yet. 87void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type, 88 bool OmitOnError) { 89 if (OmitOnError && getDiags().hasErrorOccurred()) 90 return; 91 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 92 "cannot compile this %0 yet"); 93 std::string Msg = Type; 94 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 95} 96 97/// setGlobalVisibility - Set the visibility for the given LLVM 98/// GlobalValue according to the given clang AST visibility value. 99static void setGlobalVisibility(llvm::GlobalValue *GV, 100 VisibilityAttr::VisibilityTypes Vis) { 101 switch (Vis) { 102 default: assert(0 && "Unknown visibility!"); 103 case VisibilityAttr::DefaultVisibility: 104 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 105 break; 106 case VisibilityAttr::HiddenVisibility: 107 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 108 break; 109 case VisibilityAttr::ProtectedVisibility: 110 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 111 break; 112 } 113} 114 115/// \brief Retrieves the mangled name for the given declaration. 116/// 117/// If the given declaration requires a mangled name, returns an 118/// const char* containing the mangled name. Otherwise, returns 119/// the unmangled name. 120/// 121/// FIXME: Returning an IdentifierInfo* here is a total hack. We 122/// really need some kind of string abstraction that either stores a 123/// mangled name or stores an IdentifierInfo*. This will require 124/// changes to the GlobalDeclMap, too. (I disagree, I think what we 125/// actually need is for Sema to provide some notion of which Decls 126/// refer to the same semantic decl. We shouldn't need to mangle the 127/// names and see what comes out the same to figure this out. - DWD) 128/// 129/// FIXME: Performance here is going to be terribly until we start 130/// caching mangled names. However, we should fix the problem above 131/// first. 132const char *CodeGenModule::getMangledName(const NamedDecl *ND) { 133 // In C, functions with no attributes never need to be mangled. Fastpath them. 134 if (!getLangOptions().CPlusPlus && !ND->hasAttrs()) { 135 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl."); 136 return ND->getNameAsCString(); 137 } 138 139 llvm::SmallString<256> Name; 140 llvm::raw_svector_ostream Out(Name); 141 if (!mangleName(ND, Context, Out)) { 142 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl."); 143 return ND->getNameAsCString(); 144 } 145 146 Name += '\0'; 147 return MangledNames.GetOrCreateValue(Name.begin(), Name.end()).getKeyData(); 148} 149 150/// AddGlobalCtor - Add a function to the list that will be called before 151/// main() runs. 152void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 153 // FIXME: Type coercion of void()* types. 154 GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 155} 156 157/// AddGlobalDtor - Add a function to the list that will be called 158/// when the module is unloaded. 159void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 160 // FIXME: Type coercion of void()* types. 161 GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 162} 163 164void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 165 // Ctor function type is void()*. 166 llvm::FunctionType* CtorFTy = 167 llvm::FunctionType::get(llvm::Type::VoidTy, 168 std::vector<const llvm::Type*>(), 169 false); 170 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 171 172 // Get the type of a ctor entry, { i32, void ()* }. 173 llvm::StructType* CtorStructTy = 174 llvm::StructType::get(llvm::Type::Int32Ty, 175 llvm::PointerType::getUnqual(CtorFTy), NULL); 176 177 // Construct the constructor and destructor arrays. 178 std::vector<llvm::Constant*> Ctors; 179 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 180 std::vector<llvm::Constant*> S; 181 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false)); 182 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)); 183 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 184 } 185 186 if (!Ctors.empty()) { 187 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 188 new llvm::GlobalVariable(AT, false, 189 llvm::GlobalValue::AppendingLinkage, 190 llvm::ConstantArray::get(AT, Ctors), 191 GlobalName, 192 &TheModule); 193 } 194} 195 196void CodeGenModule::EmitAnnotations() { 197 if (Annotations.empty()) 198 return; 199 200 // Create a new global variable for the ConstantStruct in the Module. 201 llvm::Constant *Array = 202 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(), 203 Annotations.size()), 204 Annotations); 205 llvm::GlobalValue *gv = 206 new llvm::GlobalVariable(Array->getType(), false, 207 llvm::GlobalValue::AppendingLinkage, Array, 208 "llvm.global.annotations", &TheModule); 209 gv->setSection("llvm.metadata"); 210} 211 212void CodeGenModule::SetGlobalValueAttributes(const Decl *D, 213 bool IsInternal, 214 bool IsInline, 215 llvm::GlobalValue *GV, 216 bool ForDefinition) { 217 // FIXME: Set up linkage and many other things. Note, this is a simple 218 // approximation of what we really want. 219 if (!ForDefinition) { 220 // Only a few attributes are set on declarations. 221 if (D->getAttr<DLLImportAttr>()) { 222 // The dllimport attribute is overridden by a subsequent declaration as 223 // dllexport. 224 if (!D->getAttr<DLLExportAttr>()) { 225 // dllimport attribute can be applied only to function decls, not to 226 // definitions. 227 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 228 if (!FD->getBody()) 229 GV->setLinkage(llvm::Function::DLLImportLinkage); 230 } else 231 GV->setLinkage(llvm::Function::DLLImportLinkage); 232 } 233 } else if (D->getAttr<WeakAttr>() || 234 D->getAttr<WeakImportAttr>()) { 235 // "extern_weak" is overloaded in LLVM; we probably should have 236 // separate linkage types for this. 237 GV->setLinkage(llvm::Function::ExternalWeakLinkage); 238 } 239 } else { 240 if (IsInternal) { 241 GV->setLinkage(llvm::Function::InternalLinkage); 242 } else { 243 if (D->getAttr<DLLExportAttr>()) { 244 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 245 // The dllexport attribute is ignored for undefined symbols. 246 if (FD->getBody()) 247 GV->setLinkage(llvm::Function::DLLExportLinkage); 248 } else 249 GV->setLinkage(llvm::Function::DLLExportLinkage); 250 } else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>() || 251 IsInline) 252 GV->setLinkage(llvm::Function::WeakAnyLinkage); 253 } 254 } 255 256 // FIXME: Figure out the relative priority of the attribute, 257 // -fvisibility, and private_extern. 258 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) 259 setGlobalVisibility(GV, attr->getVisibility()); 260 // FIXME: else handle -fvisibility 261 262 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 263 GV->setSection(SA->getName()); 264 265 // Only add to llvm.used when we see a definition, otherwise we 266 // might add multiple times or risk the value being replaced by a 267 // subsequent RAUW. 268 if (ForDefinition) { 269 if (D->getAttr<UsedAttr>()) 270 AddUsedGlobal(GV); 271 } 272} 273 274void CodeGenModule::SetFunctionAttributes(const Decl *D, 275 const CGFunctionInfo &Info, 276 llvm::Function *F) { 277 AttributeListType AttributeList; 278 ConstructAttributeList(Info, D, AttributeList); 279 280 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(), 281 AttributeList.size())); 282 283 // Set the appropriate calling convention for the Function. 284 if (D->getAttr<FastCallAttr>()) 285 F->setCallingConv(llvm::CallingConv::X86_FastCall); 286 287 if (D->getAttr<StdCallAttr>()) 288 F->setCallingConv(llvm::CallingConv::X86_StdCall); 289 290 if (D->getAttr<RegparmAttr>()) 291 ErrorUnsupported(D, "regparm attribute"); 292} 293 294/// SetFunctionAttributesForDefinition - Set function attributes 295/// specific to a function definition. 296void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D, 297 llvm::Function *F) { 298 if (isa<ObjCMethodDecl>(D)) { 299 SetGlobalValueAttributes(D, true, false, F, true); 300 } else { 301 const FunctionDecl *FD = cast<FunctionDecl>(D); 302 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static, 303 FD->isInline(), F, true); 304 } 305 306 if (!Features.Exceptions && !Features.ObjCNonFragileABI) 307 F->addFnAttr(llvm::Attribute::NoUnwind); 308 309 if (D->getAttr<AlwaysInlineAttr>()) 310 F->addFnAttr(llvm::Attribute::AlwaysInline); 311 312 if (D->getAttr<NoinlineAttr>()) 313 F->addFnAttr(llvm::Attribute::NoInline); 314 315 if (D->getAttr<RegparmAttr>()) 316 ErrorUnsupported(D, "regparm attribute"); 317} 318 319void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD, 320 llvm::Function *F) { 321 SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F); 322 323 SetFunctionAttributesForDefinition(MD, F); 324} 325 326void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD, 327 llvm::Function *F) { 328 SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F); 329 330 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static, 331 FD->isInline(), F, false); 332} 333 334void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) { 335 assert(!GV->isDeclaration() && 336 "Only globals with definition can force usage."); 337 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 338 LLVMUsed.push_back(llvm::ConstantExpr::getBitCast(GV, i8PTy)); 339} 340 341void CodeGenModule::EmitLLVMUsed() { 342 // Don't create llvm.used if there is no need. 343 if (LLVMUsed.empty()) 344 return; 345 346 llvm::ArrayType *ATy = llvm::ArrayType::get(LLVMUsed[0]->getType(), 347 LLVMUsed.size()); 348 llvm::GlobalVariable *GV = 349 new llvm::GlobalVariable(ATy, false, 350 llvm::GlobalValue::AppendingLinkage, 351 llvm::ConstantArray::get(ATy, LLVMUsed), 352 "llvm.used", &getModule()); 353 354 GV->setSection("llvm.metadata"); 355} 356 357void CodeGenModule::EmitDeferred() { 358 // Emit code for any potentially referenced deferred decls. Since a 359 // previously unused static decl may become used during the generation of code 360 // for a static function, iterate until no changes are made. 361 while (!DeferredDeclsToEmit.empty()) { 362 const ValueDecl *D = DeferredDeclsToEmit.back(); 363 DeferredDeclsToEmit.pop_back(); 364 365 // The mangled name for the decl must have been emitted in GlobalDeclMap. 366 // Look it up to see if it was defined with a stronger definition (e.g. an 367 // extern inline function with a strong function redefinition). If so, 368 // just ignore the deferred decl. 369 llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)]; 370 assert(CGRef && "Deferred decl wasn't referenced?"); 371 372 if (!CGRef->isDeclaration()) 373 continue; 374 375 // Otherwise, emit the definition and move on to the next one. 376 EmitGlobalDefinition(D); 377 } 378} 379 380/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the 381/// annotation information for a given GlobalValue. The annotation struct is 382/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 383/// GlobalValue being annotated. The second field is the constant string 384/// created from the AnnotateAttr's annotation. The third field is a constant 385/// string containing the name of the translation unit. The fourth field is 386/// the line number in the file of the annotated value declaration. 387/// 388/// FIXME: this does not unique the annotation string constants, as llvm-gcc 389/// appears to. 390/// 391llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 392 const AnnotateAttr *AA, 393 unsigned LineNo) { 394 llvm::Module *M = &getModule(); 395 396 // get [N x i8] constants for the annotation string, and the filename string 397 // which are the 2nd and 3rd elements of the global annotation structure. 398 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 399 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true); 400 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(), 401 true); 402 403 // Get the two global values corresponding to the ConstantArrays we just 404 // created to hold the bytes of the strings. 405 llvm::GlobalValue *annoGV = 406 new llvm::GlobalVariable(anno->getType(), false, 407 llvm::GlobalValue::InternalLinkage, anno, 408 GV->getName() + ".str", M); 409 // translation unit name string, emitted into the llvm.metadata section. 410 llvm::GlobalValue *unitGV = 411 new llvm::GlobalVariable(unit->getType(), false, 412 llvm::GlobalValue::InternalLinkage, unit, ".str", M); 413 414 // Create the ConstantStruct that is the global annotion. 415 llvm::Constant *Fields[4] = { 416 llvm::ConstantExpr::getBitCast(GV, SBP), 417 llvm::ConstantExpr::getBitCast(annoGV, SBP), 418 llvm::ConstantExpr::getBitCast(unitGV, SBP), 419 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo) 420 }; 421 return llvm::ConstantStruct::get(Fields, 4, false); 422} 423 424bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 425 // Never defer when EmitAllDecls is specified or the decl has 426 // attribute used. 427 if (Features.EmitAllDecls || Global->getAttr<UsedAttr>()) 428 return false; 429 430 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 431 // Constructors and destructors should never be deferred. 432 if (FD->getAttr<ConstructorAttr>() || FD->getAttr<DestructorAttr>()) 433 return false; 434 435 // FIXME: What about inline, and/or extern inline? 436 if (FD->getStorageClass() != FunctionDecl::Static) 437 return false; 438 } else { 439 const VarDecl *VD = cast<VarDecl>(Global); 440 assert(VD->isFileVarDecl() && "Invalid decl"); 441 442 if (VD->getStorageClass() != VarDecl::Static) 443 return false; 444 } 445 446 return true; 447} 448 449void CodeGenModule::EmitGlobal(const ValueDecl *Global) { 450 // If this is an alias definition (which otherwise looks like a declaration) 451 // emit it now. 452 if (Global->getAttr<AliasAttr>()) 453 return EmitAliasDefinition(Global); 454 455 // Ignore declarations, they will be emitted on their first use. 456 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 457 // Forward declarations are emitted lazily on first use. 458 if (!FD->isThisDeclarationADefinition()) 459 return; 460 } else { 461 const VarDecl *VD = cast<VarDecl>(Global); 462 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 463 464 // Forward declarations are emitted lazily on first use. 465 if (!VD->getInit() && VD->hasExternalStorage()) 466 return; 467 } 468 469 // Defer code generation when possible if this is a static definition, inline 470 // function etc. These we only want to emit if they are used. 471 if (MayDeferGeneration(Global)) { 472 // If the value has already been used, add it directly to the 473 // DeferredDeclsToEmit list. 474 const char *MangledName = getMangledName(Global); 475 if (GlobalDeclMap.count(MangledName)) 476 DeferredDeclsToEmit.push_back(Global); 477 else { 478 // Otherwise, remember that we saw a deferred decl with this name. The 479 // first use of the mangled name will cause it to move into 480 // DeferredDeclsToEmit. 481 DeferredDecls[MangledName] = Global; 482 } 483 return; 484 } 485 486 // Otherwise emit the definition. 487 EmitGlobalDefinition(Global); 488} 489 490void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) { 491 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 492 EmitGlobalFunctionDefinition(FD); 493 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 494 EmitGlobalVarDefinition(VD); 495 } else { 496 assert(0 && "Invalid argument to EmitGlobalDefinition()"); 497 } 498} 499 500/// GetOrCreateLLVMFunction - If the specified mangled name is not in the 501/// module, create and return an llvm Function with the specified type. If there 502/// is something in the module with the specified name, return it potentially 503/// bitcasted to the right type. 504/// 505/// If D is non-null, it specifies a decl that correspond to this. This is used 506/// to set the attributes on the function when it is first created. 507llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName, 508 const llvm::Type *Ty, 509 const FunctionDecl *D) { 510 // Lookup the entry, lazily creating it if necessary. 511 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName]; 512 if (Entry) { 513 if (Entry->getType()->getElementType() == Ty) 514 return Entry; 515 516 // Make sure the result is of the correct type. 517 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 518 return llvm::ConstantExpr::getBitCast(Entry, PTy); 519 } 520 521 // This is the first use or definition of a mangled name. If there is a 522 // deferred decl with this name, remember that we need to emit it at the end 523 // of the file. 524 llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI = 525 DeferredDecls.find(MangledName); 526 if (DDI != DeferredDecls.end()) { 527 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 528 // list, and remove it from DeferredDecls (since we don't need it anymore). 529 DeferredDeclsToEmit.push_back(DDI->second); 530 DeferredDecls.erase(DDI); 531 } 532 533 // This function doesn't have a complete type (for example, the return 534 // type is an incomplete struct). Use a fake type instead, and make 535 // sure not to try to set attributes. 536 bool ShouldSetAttributes = true; 537 if (!isa<llvm::FunctionType>(Ty)) { 538 Ty = llvm::FunctionType::get(llvm::Type::VoidTy, 539 std::vector<const llvm::Type*>(), false); 540 ShouldSetAttributes = false; 541 } 542 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty), 543 llvm::Function::ExternalLinkage, 544 "", &getModule()); 545 F->setName(MangledName); 546 if (D && ShouldSetAttributes) 547 SetFunctionAttributes(D, F); 548 Entry = F; 549 return F; 550} 551 552/// GetAddrOfFunction - Return the address of the given function. If Ty is 553/// non-null, then this function will use the specified type if it has to 554/// create it (this occurs when we see a definition of the function). 555llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D, 556 const llvm::Type *Ty) { 557 // If there was no specific requested type, just convert it now. 558 if (!Ty) 559 Ty = getTypes().ConvertType(D->getType()); 560 return GetOrCreateLLVMFunction(getMangledName(D), Ty, D); 561} 562 563/// CreateRuntimeFunction - Create a new runtime function with the specified 564/// type and name. 565llvm::Constant * 566CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy, 567 const char *Name) { 568 // Convert Name to be a uniqued string from the IdentifierInfo table. 569 Name = getContext().Idents.get(Name).getName(); 570 return GetOrCreateLLVMFunction(Name, FTy, 0); 571} 572 573/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 574/// create and return an llvm GlobalVariable with the specified type. If there 575/// is something in the module with the specified name, return it potentially 576/// bitcasted to the right type. 577/// 578/// If D is non-null, it specifies a decl that correspond to this. This is used 579/// to set the attributes on the global when it is first created. 580llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName, 581 const llvm::PointerType*Ty, 582 const VarDecl *D) { 583 // Lookup the entry, lazily creating it if necessary. 584 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName]; 585 if (Entry) { 586 if (Entry->getType() == Ty) 587 return Entry; 588 589 // Make sure the result is of the correct type. 590 return llvm::ConstantExpr::getBitCast(Entry, Ty); 591 } 592 593 // This is the first use or definition of a mangled name. If there is a 594 // deferred decl with this name, remember that we need to emit it at the end 595 // of the file. 596 llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI = 597 DeferredDecls.find(MangledName); 598 if (DDI != DeferredDecls.end()) { 599 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 600 // list, and remove it from DeferredDecls (since we don't need it anymore). 601 DeferredDeclsToEmit.push_back(DDI->second); 602 DeferredDecls.erase(DDI); 603 } 604 605 llvm::GlobalVariable *GV = 606 new llvm::GlobalVariable(Ty->getElementType(), false, 607 llvm::GlobalValue::ExternalLinkage, 608 0, "", &getModule(), 609 0, Ty->getAddressSpace()); 610 GV->setName(MangledName); 611 612 // Handle things which are present even on external declarations. 613 if (D) { 614 // FIXME: This code is overly simple and should be merged with 615 // other global handling. 616 GV->setConstant(D->getType().isConstant(Context)); 617 618 // FIXME: Merge with other attribute handling code. 619 if (D->getStorageClass() == VarDecl::PrivateExtern) 620 setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility); 621 622 if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>()) 623 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 624 } 625 626 return Entry = GV; 627} 628 629 630/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 631/// given global variable. If Ty is non-null and if the global doesn't exist, 632/// then it will be greated with the specified type instead of whatever the 633/// normal requested type would be. 634llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 635 const llvm::Type *Ty) { 636 assert(D->hasGlobalStorage() && "Not a global variable"); 637 QualType ASTTy = D->getType(); 638 if (Ty == 0) 639 Ty = getTypes().ConvertTypeForMem(ASTTy); 640 641 const llvm::PointerType *PTy = 642 llvm::PointerType::get(Ty, ASTTy.getAddressSpace()); 643 return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D); 644} 645 646/// CreateRuntimeVariable - Create a new runtime global variable with the 647/// specified type and name. 648llvm::Constant * 649CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty, 650 const char *Name) { 651 // Convert Name to be a uniqued string from the IdentifierInfo table. 652 Name = getContext().Idents.get(Name).getName(); 653 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0); 654} 655 656void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 657 llvm::Constant *Init = 0; 658 QualType ASTTy = D->getType(); 659 660 if (D->getInit() == 0) { 661 // This is a tentative definition; tentative definitions are 662 // implicitly initialized with { 0 } 663 const llvm::Type *InitTy = getTypes().ConvertTypeForMem(ASTTy); 664 if (ASTTy->isIncompleteArrayType()) { 665 // An incomplete array is normally [ TYPE x 0 ], but we need 666 // to fix it to [ TYPE x 1 ]. 667 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(InitTy); 668 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1); 669 } 670 Init = llvm::Constant::getNullValue(InitTy); 671 } else { 672 Init = EmitConstantExpr(D->getInit()); 673 if (!Init) { 674 ErrorUnsupported(D, "static initializer"); 675 QualType T = D->getInit()->getType(); 676 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 677 } 678 } 679 680 const llvm::Type* InitType = Init->getType(); 681 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 682 683 // Strip off a bitcast if we got one back. 684 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 685 assert(CE->getOpcode() == llvm::Instruction::BitCast); 686 Entry = CE->getOperand(0); 687 } 688 689 // Entry is now either a Function or GlobalVariable. 690 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 691 692 // If we already have this global and it has an initializer, then 693 // we are in the rare situation where we emitted the defining 694 // declaration of the global and are now being asked to emit a 695 // definition which would be common. This occurs, for example, in 696 // the following situation because statics can be emitted out of 697 // order: 698 // 699 // static int x; 700 // static int *y = &x; 701 // static int x = 10; 702 // int **z = &y; 703 // 704 // Bail here so we don't blow away the definition. Note that if we 705 // can't distinguish here if we emitted a definition with a null 706 // initializer, but this case is safe. 707 if (GV && GV->hasInitializer() && !GV->getInitializer()->isNullValue()) { 708 assert(!D->getInit() && "Emitting multiple definitions of a decl!"); 709 return; 710 } 711 712 // We have a definition after a declaration with the wrong type. 713 // We must make a new GlobalVariable* and update everything that used OldGV 714 // (a declaration or tentative definition) with the new GlobalVariable* 715 // (which will be a definition). 716 // 717 // This happens if there is a prototype for a global (e.g. 718 // "extern int x[];") and then a definition of a different type (e.g. 719 // "int x[10];"). This also happens when an initializer has a different type 720 // from the type of the global (this happens with unions). 721 // 722 // FIXME: This also ends up happening if there's a definition followed by 723 // a tentative definition! (Although Sema rejects that construct 724 // at the moment.) 725 if (GV == 0 || 726 GV->getType()->getElementType() != InitType || 727 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) { 728 729 // Remove the old entry from GlobalDeclMap so that we'll create a new one. 730 GlobalDeclMap.erase(getMangledName(D)); 731 732 // Make a new global with the correct type, this is now guaranteed to work. 733 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 734 GV->takeName(cast<llvm::GlobalValue>(Entry)); 735 736 // Replace all uses of the old global with the new global 737 llvm::Constant *NewPtrForOldDecl = 738 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 739 Entry->replaceAllUsesWith(NewPtrForOldDecl); 740 741 // Erase the old global, since it is no longer used. 742 // FIXME: What if it was attribute used? Dangling pointer from LLVMUsed. 743 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 744 } 745 746 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) { 747 SourceManager &SM = Context.getSourceManager(); 748 AddAnnotation(EmitAnnotateAttr(GV, AA, 749 SM.getInstantiationLineNumber(D->getLocation()))); 750 } 751 752 GV->setInitializer(Init); 753 GV->setConstant(D->getType().isConstant(Context)); 754 GV->setAlignment(getContext().getDeclAlignInBytes(D)); 755 756 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) 757 setGlobalVisibility(GV, attr->getVisibility()); 758 // FIXME: else handle -fvisibility 759 760 // Set the llvm linkage type as appropriate. 761 if (D->getStorageClass() == VarDecl::Static) 762 GV->setLinkage(llvm::Function::InternalLinkage); 763 else if (D->getAttr<DLLImportAttr>()) 764 GV->setLinkage(llvm::Function::DLLImportLinkage); 765 else if (D->getAttr<DLLExportAttr>()) 766 GV->setLinkage(llvm::Function::DLLExportLinkage); 767 else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>()) 768 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 769 else { 770 // FIXME: This isn't right. This should handle common linkage and other 771 // stuff. 772 switch (D->getStorageClass()) { 773 case VarDecl::Static: assert(0 && "This case handled above"); 774 case VarDecl::Auto: 775 case VarDecl::Register: 776 assert(0 && "Can't have auto or register globals"); 777 case VarDecl::None: 778 if (!D->getInit() && !CompileOpts.NoCommon) 779 GV->setLinkage(llvm::GlobalVariable::CommonLinkage); 780 else 781 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage); 782 break; 783 case VarDecl::Extern: 784 // FIXME: common 785 break; 786 787 case VarDecl::PrivateExtern: 788 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 789 // FIXME: common 790 break; 791 } 792 } 793 794 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 795 GV->setSection(SA->getName()); 796 797 if (D->getAttr<UsedAttr>()) 798 AddUsedGlobal(GV); 799 800 // Emit global variable debug information. 801 if (CGDebugInfo *DI = getDebugInfo()) { 802 DI->setLocation(D->getLocation()); 803 DI->EmitGlobalVariable(GV, D); 804 } 805} 806 807 808void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) { 809 const llvm::FunctionType *Ty = 810 cast<llvm::FunctionType>(getTypes().ConvertType(D->getType())); 811 812 // As a special case, make sure that definitions of K&R function 813 // "type foo()" aren't declared as varargs (which forces the backend 814 // to do unnecessary work). 815 if (D->getType()->isFunctionNoProtoType()) { 816 assert(Ty->isVarArg() && "Didn't lower type as expected"); 817 // Due to stret, the lowered function could have arguments. Just create the 818 // same type as was lowered by ConvertType but strip off the varargs bit. 819 std::vector<const llvm::Type*> Args(Ty->param_begin(), Ty->param_end()); 820 Ty = llvm::FunctionType::get(Ty->getReturnType(), Args, false); 821 } 822 823 // Get or create the prototype for teh function. 824 llvm::Constant *Entry = GetAddrOfFunction(D, Ty); 825 826 // Strip off a bitcast if we got one back. 827 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 828 assert(CE->getOpcode() == llvm::Instruction::BitCast); 829 Entry = CE->getOperand(0); 830 } 831 832 833 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 834 // If the types mismatch then we have to rewrite the definition. 835 assert(cast<llvm::GlobalValue>(Entry)->isDeclaration() && 836 "Shouldn't replace non-declaration"); 837 838 // F is the Function* for the one with the wrong type, we must make a new 839 // Function* and update everything that used F (a declaration) with the new 840 // Function* (which will be a definition). 841 // 842 // This happens if there is a prototype for a function 843 // (e.g. "int f()") and then a definition of a different type 844 // (e.g. "int f(int x)"). Start by making a new function of the 845 // correct type, RAUW, then steal the name. 846 GlobalDeclMap.erase(getMangledName(D)); 847 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(D, Ty)); 848 NewFn->takeName(cast<llvm::GlobalValue>(Entry)); 849 850 // Replace uses of F with the Function we will endow with a body. 851 llvm::Constant *NewPtrForOldDecl = 852 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 853 Entry->replaceAllUsesWith(NewPtrForOldDecl); 854 855 // Ok, delete the old function now, which is dead. 856 // FIXME: If it was attribute(used) the pointer will dangle from the 857 // LLVMUsed array! 858 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 859 860 Entry = NewFn; 861 } 862 863 llvm::Function *Fn = cast<llvm::Function>(Entry); 864 865 CodeGenFunction(*this).GenerateCode(D, Fn); 866 867 SetFunctionAttributesForDefinition(D, Fn); 868 869 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 870 AddGlobalCtor(Fn, CA->getPriority()); 871 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 872 AddGlobalDtor(Fn, DA->getPriority()); 873} 874 875void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) { 876 const AliasAttr *AA = D->getAttr<AliasAttr>(); 877 assert(AA && "Not an alias?"); 878 879 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 880 881 // Unique the name through the identifier table. 882 const char *AliaseeName = AA->getAliasee().c_str(); 883 AliaseeName = getContext().Idents.get(AliaseeName).getName(); 884 885 // Create a reference to the named value. This ensures that it is emitted 886 // if a deferred decl. 887 llvm::Constant *Aliasee; 888 if (isa<llvm::FunctionType>(DeclTy)) 889 Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, 0); 890 else 891 Aliasee = GetOrCreateLLVMGlobal(AliaseeName, 892 llvm::PointerType::getUnqual(DeclTy), 0); 893 894 // Create the new alias itself, but don't set a name yet. 895 llvm::GlobalValue *GA = 896 new llvm::GlobalAlias(Aliasee->getType(), 897 llvm::Function::ExternalLinkage, 898 "", Aliasee, &getModule()); 899 900 // See if there is already something with the alias' name in the module. 901 const char *MangledName = getMangledName(D); 902 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName]; 903 904 if (Entry && !Entry->isDeclaration()) { 905 // If there is a definition in the module, then it wins over the alias. 906 // This is dubious, but allow it to be safe. Just ignore the alias. 907 GA->eraseFromParent(); 908 return; 909 } 910 911 if (Entry) { 912 // If there is a declaration in the module, then we had an extern followed 913 // by the alias, as in: 914 // extern int test6(); 915 // ... 916 // int test6() __attribute__((alias("test7"))); 917 // 918 // Remove it and replace uses of it with the alias. 919 920 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 921 Entry->getType())); 922 // FIXME: What if it was attribute used? Dangling pointer from LLVMUsed. 923 Entry->eraseFromParent(); 924 } 925 926 // Now we know that there is no conflict, set the name. 927 Entry = GA; 928 GA->setName(MangledName); 929 930 // Alias should never be internal or inline. 931 SetGlobalValueAttributes(D, false, false, GA, true); 932} 933 934void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 935 // Make sure that this type is translated. 936 Types.UpdateCompletedType(TD); 937} 938 939 940/// getBuiltinLibFunction - Given a builtin id for a function like 941/// "__builtin_fabsf", return a Function* for "fabsf". 942llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) { 943 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) || 944 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) && 945 "isn't a lib fn"); 946 947 // Get the name, skip over the __builtin_ prefix (if necessary). 948 const char *Name = Context.BuiltinInfo.GetName(BuiltinID); 949 if (Context.BuiltinInfo.isLibFunction(BuiltinID)) 950 Name += 10; 951 952 // Get the type for the builtin. 953 Builtin::Context::GetBuiltinTypeError Error; 954 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error); 955 assert(Error == Builtin::Context::GE_None && "Can't get builtin type"); 956 957 const llvm::FunctionType *Ty = 958 cast<llvm::FunctionType>(getTypes().ConvertType(Type)); 959 960 // Unique the name through the identifier table. 961 Name = getContext().Idents.get(Name).getName(); 962 // FIXME: param attributes for sext/zext etc. 963 return GetOrCreateLLVMFunction(Name, Ty, 0); 964} 965 966llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys, 967 unsigned NumTys) { 968 return llvm::Intrinsic::getDeclaration(&getModule(), 969 (llvm::Intrinsic::ID)IID, Tys, NumTys); 970} 971 972llvm::Function *CodeGenModule::getMemCpyFn() { 973 if (MemCpyFn) return MemCpyFn; 974 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(); 975 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1); 976} 977 978llvm::Function *CodeGenModule::getMemMoveFn() { 979 if (MemMoveFn) return MemMoveFn; 980 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(); 981 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1); 982} 983 984llvm::Function *CodeGenModule::getMemSetFn() { 985 if (MemSetFn) return MemSetFn; 986 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(); 987 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1); 988} 989 990static void appendFieldAndPadding(CodeGenModule &CGM, 991 std::vector<llvm::Constant*>& Fields, 992 FieldDecl *FieldD, FieldDecl *NextFieldD, 993 llvm::Constant* Field, 994 RecordDecl* RD, const llvm::StructType *STy) { 995 // Append the field. 996 Fields.push_back(Field); 997 998 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD); 999 1000 int NextStructFieldNo; 1001 if (!NextFieldD) { 1002 NextStructFieldNo = STy->getNumElements(); 1003 } else { 1004 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD); 1005 } 1006 1007 // Append padding 1008 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) { 1009 llvm::Constant *C = 1010 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1)); 1011 1012 Fields.push_back(C); 1013 } 1014} 1015 1016// We still need to work out the details of handling UTF-16. 1017// See: <rdr://2996215> 1018llvm::Constant *CodeGenModule:: 1019GetAddrOfConstantCFString(const std::string &str) { 1020 llvm::StringMapEntry<llvm::Constant *> &Entry = 1021 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 1022 1023 if (Entry.getValue()) 1024 return Entry.getValue(); 1025 1026 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty); 1027 llvm::Constant *Zeros[] = { Zero, Zero }; 1028 1029 if (!CFConstantStringClassRef) { 1030 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1031 Ty = llvm::ArrayType::get(Ty, 0); 1032 1033 // FIXME: This is fairly broken if 1034 // __CFConstantStringClassReference is already defined, in that it 1035 // will get renamed and the user will most likely see an opaque 1036 // error message. This is a general issue with relying on 1037 // particular names. 1038 llvm::GlobalVariable *GV = 1039 new llvm::GlobalVariable(Ty, false, 1040 llvm::GlobalVariable::ExternalLinkage, 0, 1041 "__CFConstantStringClassReference", 1042 &getModule()); 1043 1044 // Decay array -> ptr 1045 CFConstantStringClassRef = 1046 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1047 } 1048 1049 QualType CFTy = getContext().getCFConstantStringType(); 1050 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl(); 1051 1052 const llvm::StructType *STy = 1053 cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 1054 1055 std::vector<llvm::Constant*> Fields; 1056 RecordDecl::field_iterator Field = CFRD->field_begin(); 1057 1058 // Class pointer. 1059 FieldDecl *CurField = *Field++; 1060 FieldDecl *NextField = *Field++; 1061 appendFieldAndPadding(*this, Fields, CurField, NextField, 1062 CFConstantStringClassRef, CFRD, STy); 1063 1064 // Flags. 1065 CurField = NextField; 1066 NextField = *Field++; 1067 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1068 appendFieldAndPadding(*this, Fields, CurField, NextField, 1069 llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy); 1070 1071 // String pointer. 1072 CurField = NextField; 1073 NextField = *Field++; 1074 llvm::Constant *C = llvm::ConstantArray::get(str); 1075 C = new llvm::GlobalVariable(C->getType(), true, 1076 llvm::GlobalValue::InternalLinkage, 1077 C, ".str", &getModule()); 1078 appendFieldAndPadding(*this, Fields, CurField, NextField, 1079 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2), 1080 CFRD, STy); 1081 1082 // String length. 1083 CurField = NextField; 1084 NextField = 0; 1085 Ty = getTypes().ConvertType(getContext().LongTy); 1086 appendFieldAndPadding(*this, Fields, CurField, NextField, 1087 llvm::ConstantInt::get(Ty, str.length()), CFRD, STy); 1088 1089 // The struct. 1090 C = llvm::ConstantStruct::get(STy, Fields); 1091 llvm::GlobalVariable *GV = 1092 new llvm::GlobalVariable(C->getType(), true, 1093 llvm::GlobalVariable::InternalLinkage, 1094 C, "", &getModule()); 1095 1096 GV->setSection("__DATA,__cfstring"); 1097 Entry.setValue(GV); 1098 1099 return GV; 1100} 1101 1102/// GetStringForStringLiteral - Return the appropriate bytes for a 1103/// string literal, properly padded to match the literal type. 1104std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) { 1105 const char *StrData = E->getStrData(); 1106 unsigned Len = E->getByteLength(); 1107 1108 const ConstantArrayType *CAT = 1109 getContext().getAsConstantArrayType(E->getType()); 1110 assert(CAT && "String isn't pointer or array!"); 1111 1112 // Resize the string to the right size. 1113 std::string Str(StrData, StrData+Len); 1114 uint64_t RealLen = CAT->getSize().getZExtValue(); 1115 1116 if (E->isWide()) 1117 RealLen *= getContext().Target.getWCharWidth()/8; 1118 1119 Str.resize(RealLen, '\0'); 1120 1121 return Str; 1122} 1123 1124/// GetAddrOfConstantStringFromLiteral - Return a pointer to a 1125/// constant array for the given string literal. 1126llvm::Constant * 1127CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 1128 // FIXME: This can be more efficient. 1129 return GetAddrOfConstantString(GetStringForStringLiteral(S)); 1130} 1131 1132/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 1133/// array for the given ObjCEncodeExpr node. 1134llvm::Constant * 1135CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 1136 std::string Str; 1137 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 1138 1139 return GetAddrOfConstantCString(Str); 1140} 1141 1142 1143/// GenerateWritableString -- Creates storage for a string literal. 1144static llvm::Constant *GenerateStringLiteral(const std::string &str, 1145 bool constant, 1146 CodeGenModule &CGM, 1147 const char *GlobalName) { 1148 // Create Constant for this string literal. Don't add a '\0'. 1149 llvm::Constant *C = llvm::ConstantArray::get(str, false); 1150 1151 // Create a global variable for this string 1152 return new llvm::GlobalVariable(C->getType(), constant, 1153 llvm::GlobalValue::InternalLinkage, 1154 C, GlobalName ? GlobalName : ".str", 1155 &CGM.getModule()); 1156} 1157 1158/// GetAddrOfConstantString - Returns a pointer to a character array 1159/// containing the literal. This contents are exactly that of the 1160/// given string, i.e. it will not be null terminated automatically; 1161/// see GetAddrOfConstantCString. Note that whether the result is 1162/// actually a pointer to an LLVM constant depends on 1163/// Feature.WriteableStrings. 1164/// 1165/// The result has pointer to array type. 1166llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str, 1167 const char *GlobalName) { 1168 // Don't share any string literals if writable-strings is turned on. 1169 if (Features.WritableStrings) 1170 return GenerateStringLiteral(str, false, *this, GlobalName); 1171 1172 llvm::StringMapEntry<llvm::Constant *> &Entry = 1173 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 1174 1175 if (Entry.getValue()) 1176 return Entry.getValue(); 1177 1178 // Create a global variable for this. 1179 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName); 1180 Entry.setValue(C); 1181 return C; 1182} 1183 1184/// GetAddrOfConstantCString - Returns a pointer to a character 1185/// array containing the literal and a terminating '\-' 1186/// character. The result has pointer to array type. 1187llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str, 1188 const char *GlobalName){ 1189 return GetAddrOfConstantString(str + '\0', GlobalName); 1190} 1191 1192/// EmitObjCPropertyImplementations - Emit information for synthesized 1193/// properties for an implementation. 1194void CodeGenModule::EmitObjCPropertyImplementations(const 1195 ObjCImplementationDecl *D) { 1196 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(), 1197 e = D->propimpl_end(); i != e; ++i) { 1198 ObjCPropertyImplDecl *PID = *i; 1199 1200 // Dynamic is just for type-checking. 1201 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 1202 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 1203 1204 // Determine which methods need to be implemented, some may have 1205 // been overridden. Note that ::isSynthesized is not the method 1206 // we want, that just indicates if the decl came from a 1207 // property. What we want to know is if the method is defined in 1208 // this implementation. 1209 if (!D->getInstanceMethod(PD->getGetterName())) 1210 CodeGenFunction(*this).GenerateObjCGetter( 1211 const_cast<ObjCImplementationDecl *>(D), PID); 1212 if (!PD->isReadOnly() && 1213 !D->getInstanceMethod(PD->getSetterName())) 1214 CodeGenFunction(*this).GenerateObjCSetter( 1215 const_cast<ObjCImplementationDecl *>(D), PID); 1216 } 1217 } 1218} 1219 1220/// EmitTopLevelDecl - Emit code for a single top level declaration. 1221void CodeGenModule::EmitTopLevelDecl(Decl *D) { 1222 // If an error has occurred, stop code generation, but continue 1223 // parsing and semantic analysis (to ensure all warnings and errors 1224 // are emitted). 1225 if (Diags.hasErrorOccurred()) 1226 return; 1227 1228 switch (D->getKind()) { 1229 case Decl::Function: 1230 case Decl::Var: 1231 EmitGlobal(cast<ValueDecl>(D)); 1232 break; 1233 1234 case Decl::Namespace: 1235 ErrorUnsupported(D, "namespace"); 1236 break; 1237 1238 // Objective-C Decls 1239 1240 // Forward declarations, no (immediate) code generation. 1241 case Decl::ObjCClass: 1242 case Decl::ObjCForwardProtocol: 1243 case Decl::ObjCCategory: 1244 case Decl::ObjCInterface: 1245 break; 1246 1247 case Decl::ObjCProtocol: 1248 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D)); 1249 break; 1250 1251 case Decl::ObjCCategoryImpl: 1252 // Categories have properties but don't support synthesize so we 1253 // can ignore them here. 1254 1255 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 1256 break; 1257 1258 case Decl::ObjCImplementation: { 1259 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 1260 EmitObjCPropertyImplementations(OMD); 1261 Runtime->GenerateClass(OMD); 1262 break; 1263 } 1264 case Decl::ObjCMethod: { 1265 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 1266 // If this is not a prototype, emit the body. 1267 if (OMD->getBody()) 1268 CodeGenFunction(*this).GenerateObjCMethod(OMD); 1269 break; 1270 } 1271 case Decl::ObjCCompatibleAlias: 1272 // compatibility-alias is a directive and has no code gen. 1273 break; 1274 1275 case Decl::LinkageSpec: { 1276 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D); 1277 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx) 1278 ErrorUnsupported(LSD, "linkage spec"); 1279 // FIXME: implement C++ linkage, C linkage works mostly by C 1280 // language reuse already. 1281 break; 1282 } 1283 1284 case Decl::FileScopeAsm: { 1285 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 1286 std::string AsmString(AD->getAsmString()->getStrData(), 1287 AD->getAsmString()->getByteLength()); 1288 1289 const std::string &S = getModule().getModuleInlineAsm(); 1290 if (S.empty()) 1291 getModule().setModuleInlineAsm(AsmString); 1292 else 1293 getModule().setModuleInlineAsm(S + '\n' + AsmString); 1294 break; 1295 } 1296 1297 default: 1298 // Make sure we handled everything we should, every other kind is 1299 // a non-top-level decl. FIXME: Would be nice to have an 1300 // isTopLevelDeclKind function. Need to recode Decl::Kind to do 1301 // that easily. 1302 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 1303 } 1304} 1305