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 "CGDebugInfo.h" 15 #include "CodeGenModule.h" 16 #include "CodeGenFunction.h" 17 #include "CGObjCRuntime.h" 18 #include "clang/AST/ASTContext.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/Basic/Diagnostic.h" 21 #include "clang/Basic/SourceManager.h" 22 #include "clang/Basic/TargetInfo.h" 23 #include "llvm/CallingConv.h" 24 #include "llvm/Module.h" 25 #include "llvm/Intrinsics.h" 26 #include "llvm/Target/TargetData.h" 27 #include "llvm/Analysis/Verifier.h" 28 using namespace clang; 29 using namespace CodeGen; 30 31 32 CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO, 33 llvm::Module &M, const llvm::TargetData &TD, 34 Diagnostic &diags, bool GenerateDebugInfo) 35 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags), 36 Types(C, M, TD), Runtime(0), MemCpyFn(0), MemMoveFn(0), MemSetFn(0), 37 CFConstantStringClassRef(0) { 38 39 if (Features.ObjC1) { 40 if (Features.NeXTRuntime) { 41 Runtime = CreateMacObjCRuntime(*this); 42 } else { 43 Runtime = CreateGNUObjCRuntime(*this); 44 } 45 } 46 47 // If debug info generation is enabled, create the CGDebugInfo object. 48 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0; 49 } 50 51 CodeGenModule::~CodeGenModule() { 52 delete Runtime; 53 delete DebugInfo; 54 } 55 56 void CodeGenModule::Release() { 57 EmitStatics(); 58 if (Runtime) 59 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction()) 60 AddGlobalCtor(ObjCInitFunction); 61 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 62 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 63 EmitAnnotations(); 64 // Run the verifier to check that the generated code is consistent. 65 assert(!verifyModule(TheModule)); 66 } 67 68 /// WarnUnsupported - Print out a warning that codegen doesn't support the 69 /// specified stmt yet. 70 void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) { 71 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning, 72 "cannot codegen this %0 yet"); 73 SourceRange Range = S->getSourceRange(); 74 std::string Msg = Type; 75 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID, 76 &Msg, 1, &Range, 1); 77 } 78 79 /// WarnUnsupported - Print out a warning that codegen doesn't support the 80 /// specified decl yet. 81 void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) { 82 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning, 83 "cannot codegen this %0 yet"); 84 std::string Msg = Type; 85 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID, 86 &Msg, 1); 87 } 88 89 /// setGlobalVisibility - Set the visibility for the given LLVM 90 /// GlobalValue according to the given clang AST visibility value. 91 static void setGlobalVisibility(llvm::GlobalValue *GV, 92 VisibilityAttr::VisibilityTypes Vis) { 93 switch (Vis) { 94 default: assert(0 && "Unknown visibility!"); 95 case VisibilityAttr::DefaultVisibility: 96 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 97 break; 98 case VisibilityAttr::HiddenVisibility: 99 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 100 break; 101 case VisibilityAttr::ProtectedVisibility: 102 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 103 break; 104 } 105 } 106 107 /// AddGlobalCtor - Add a function to the list that will be called before 108 /// main() runs. 109 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 110 // TODO: Type coercion of void()* types. 111 GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 112 } 113 114 /// AddGlobalDtor - Add a function to the list that will be called 115 /// when the module is unloaded. 116 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 117 // TODO: Type coercion of void()* types. 118 GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 119 } 120 121 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 122 // Ctor function type is void()*. 123 llvm::FunctionType* CtorFTy = 124 llvm::FunctionType::get(llvm::Type::VoidTy, 125 std::vector<const llvm::Type*>(), 126 false); 127 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 128 129 // Get the type of a ctor entry, { i32, void ()* }. 130 llvm::StructType* CtorStructTy = 131 llvm::StructType::get(llvm::Type::Int32Ty, 132 llvm::PointerType::getUnqual(CtorFTy), NULL); 133 134 // Construct the constructor and destructor arrays. 135 std::vector<llvm::Constant*> Ctors; 136 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 137 std::vector<llvm::Constant*> S; 138 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false)); 139 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)); 140 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 141 } 142 143 if (!Ctors.empty()) { 144 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 145 new llvm::GlobalVariable(AT, false, 146 llvm::GlobalValue::AppendingLinkage, 147 llvm::ConstantArray::get(AT, Ctors), 148 GlobalName, 149 &TheModule); 150 } 151 } 152 153 void CodeGenModule::EmitAnnotations() { 154 if (Annotations.empty()) 155 return; 156 157 // Create a new global variable for the ConstantStruct in the Module. 158 llvm::Constant *Array = 159 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(), 160 Annotations.size()), 161 Annotations); 162 llvm::GlobalValue *gv = 163 new llvm::GlobalVariable(Array->getType(), false, 164 llvm::GlobalValue::AppendingLinkage, Array, 165 "llvm.global.annotations", &TheModule); 166 gv->setSection("llvm.metadata"); 167 } 168 169 bool hasAggregateLLVMType(QualType T) { 170 return !T->isRealType() && !T->isPointerLikeType() && 171 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType(); 172 } 173 174 void CodeGenModule::SetGlobalValueAttributes(const FunctionDecl *FD, 175 llvm::GlobalValue *GV) { 176 // TODO: Set up linkage and many other things. Note, this is a simple 177 // approximation of what we really want. 178 if (FD->getStorageClass() == FunctionDecl::Static) 179 GV->setLinkage(llvm::Function::InternalLinkage); 180 else if (FD->getAttr<DLLImportAttr>()) 181 GV->setLinkage(llvm::Function::DLLImportLinkage); 182 else if (FD->getAttr<DLLExportAttr>()) 183 GV->setLinkage(llvm::Function::DLLExportLinkage); 184 else if (FD->getAttr<WeakAttr>() || FD->isInline()) 185 GV->setLinkage(llvm::Function::WeakLinkage); 186 187 if (const VisibilityAttr *attr = FD->getAttr<VisibilityAttr>()) 188 setGlobalVisibility(GV, attr->getVisibility()); 189 // FIXME: else handle -fvisibility 190 191 if (const AsmLabelAttr *ALA = FD->getAttr<AsmLabelAttr>()) { 192 // Prefaced with special LLVM marker to indicate that the name 193 // should not be munged. 194 GV->setName("\01" + ALA->getLabel()); 195 } 196 } 197 198 void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD, 199 llvm::Function *F, 200 const llvm::FunctionType *FTy) { 201 unsigned FuncAttrs = 0; 202 if (FD->getAttr<NoThrowAttr>()) 203 FuncAttrs |= llvm::ParamAttr::NoUnwind; 204 if (FD->getAttr<NoReturnAttr>()) 205 FuncAttrs |= llvm::ParamAttr::NoReturn; 206 207 llvm::SmallVector<llvm::ParamAttrsWithIndex, 8> ParamAttrList; 208 if (FuncAttrs) 209 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(0, FuncAttrs)); 210 // Note that there is parallel code in CodeGenFunction::EmitCallExpr 211 bool AggregateReturn = hasAggregateLLVMType(FD->getResultType()); 212 if (AggregateReturn) 213 ParamAttrList.push_back( 214 llvm::ParamAttrsWithIndex::get(1, llvm::ParamAttr::StructRet)); 215 unsigned increment = AggregateReturn ? 2 : 1; 216 const FunctionTypeProto* FTP = dyn_cast<FunctionTypeProto>(FD->getType()); 217 if (FTP) { 218 for (unsigned i = 0; i < FTP->getNumArgs(); i++) { 219 QualType ParamType = FTP->getArgType(i); 220 unsigned ParamAttrs = 0; 221 if (ParamType->isRecordType()) 222 ParamAttrs |= llvm::ParamAttr::ByVal; 223 if (ParamType->isSignedIntegerType() && 224 ParamType->isPromotableIntegerType()) 225 ParamAttrs |= llvm::ParamAttr::SExt; 226 if (ParamType->isUnsignedIntegerType() && 227 ParamType->isPromotableIntegerType()) 228 ParamAttrs |= llvm::ParamAttr::ZExt; 229 if (ParamAttrs) 230 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(i + increment, 231 ParamAttrs)); 232 } 233 } 234 235 F->setParamAttrs(llvm::PAListPtr::get(ParamAttrList.begin(), 236 ParamAttrList.size())); 237 238 // Set the appropriate calling convention for the Function. 239 if (FD->getAttr<FastCallAttr>()) 240 F->setCallingConv(llvm::CallingConv::Fast); 241 242 SetGlobalValueAttributes(FD, F); 243 } 244 245 void CodeGenModule::EmitStatics() { 246 // Emit code for each used static decl encountered. Since a previously unused 247 // static decl may become used during the generation of code for a static 248 // function, iterate until no changes are made. 249 bool Changed; 250 do { 251 Changed = false; 252 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) { 253 const ValueDecl *D = StaticDecls[i]; 254 255 // Check if we have used a decl with the same name 256 // FIXME: The AST should have some sort of aggregate decls or 257 // global symbol map. 258 if (!GlobalDeclMap.count(D->getName())) 259 continue; 260 261 // Emit the definition. 262 EmitGlobalDefinition(D); 263 264 // Erase the used decl from the list. 265 StaticDecls[i] = StaticDecls.back(); 266 StaticDecls.pop_back(); 267 --i; 268 --e; 269 270 // Remember that we made a change. 271 Changed = true; 272 } 273 } while (Changed); 274 } 275 276 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the 277 /// annotation information for a given GlobalValue. The annotation struct is 278 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 279 /// GlobalValue being annotated. The second field is the constant string 280 /// created from the AnnotateAttr's annotation. The third field is a constant 281 /// string containing the name of the translation unit. The fourth field is 282 /// the line number in the file of the annotated value declaration. 283 /// 284 /// FIXME: this does not unique the annotation string constants, as llvm-gcc 285 /// appears to. 286 /// 287 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 288 const AnnotateAttr *AA, 289 unsigned LineNo) { 290 llvm::Module *M = &getModule(); 291 292 // get [N x i8] constants for the annotation string, and the filename string 293 // which are the 2nd and 3rd elements of the global annotation structure. 294 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 295 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true); 296 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(), 297 true); 298 299 // Get the two global values corresponding to the ConstantArrays we just 300 // created to hold the bytes of the strings. 301 llvm::GlobalValue *annoGV = 302 new llvm::GlobalVariable(anno->getType(), false, 303 llvm::GlobalValue::InternalLinkage, anno, 304 GV->getName() + ".str", M); 305 // translation unit name string, emitted into the llvm.metadata section. 306 llvm::GlobalValue *unitGV = 307 new llvm::GlobalVariable(unit->getType(), false, 308 llvm::GlobalValue::InternalLinkage, unit, ".str", M); 309 310 // Create the ConstantStruct that is the global annotion. 311 llvm::Constant *Fields[4] = { 312 llvm::ConstantExpr::getBitCast(GV, SBP), 313 llvm::ConstantExpr::getBitCast(annoGV, SBP), 314 llvm::ConstantExpr::getBitCast(unitGV, SBP), 315 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo) 316 }; 317 return llvm::ConstantStruct::get(Fields, 4, false); 318 } 319 320 void CodeGenModule::EmitGlobal(const ValueDecl *Global) { 321 bool isDef, isStatic; 322 323 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 324 isDef = (FD->isThisDeclarationADefinition() || 325 FD->getAttr<AliasAttr>()); 326 isStatic = FD->getStorageClass() == FunctionDecl::Static; 327 } else if (const VarDecl *VD = cast<VarDecl>(Global)) { 328 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 329 330 isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0); 331 isStatic = VD->getStorageClass() == VarDecl::Static; 332 } else { 333 assert(0 && "Invalid argument to EmitGlobal"); 334 return; 335 } 336 337 // Forward declarations are emitted lazily on first use. 338 if (!isDef) 339 return; 340 341 // If the global is a static, defer code generation until later so 342 // we can easily omit unused statics. 343 if (isStatic) { 344 StaticDecls.push_back(Global); 345 return; 346 } 347 348 // Otherwise emit the definition. 349 EmitGlobalDefinition(Global); 350 } 351 352 void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) { 353 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 354 EmitGlobalFunctionDefinition(FD); 355 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 356 EmitGlobalVarDefinition(VD); 357 } else { 358 assert(0 && "Invalid argument to EmitGlobalDefinition()"); 359 } 360 } 361 362 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) { 363 assert(D->hasGlobalStorage() && "Not a global variable"); 364 365 QualType ASTTy = D->getType(); 366 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy); 367 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace()); 368 369 // Lookup the entry, lazily creating it if necessary. 370 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()]; 371 if (!Entry) 372 Entry = new llvm::GlobalVariable(Ty, false, 373 llvm::GlobalValue::ExternalLinkage, 374 0, D->getName(), &getModule(), 0, 375 ASTTy.getAddressSpace()); 376 377 // Make sure the result is of the correct type. 378 return llvm::ConstantExpr::getBitCast(Entry, PTy); 379 } 380 381 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 382 llvm::Constant *Init = 0; 383 QualType ASTTy = D->getType(); 384 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy); 385 386 if (D->getInit() == 0) { 387 // This is a tentative definition; tentative definitions are 388 // implicitly initialized with { 0 } 389 const llvm::Type* InitTy; 390 if (ASTTy->isIncompleteArrayType()) { 391 // An incomplete array is normally [ TYPE x 0 ], but we need 392 // to fix it to [ TYPE x 1 ]. 393 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy); 394 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1); 395 } else { 396 InitTy = VarTy; 397 } 398 Init = llvm::Constant::getNullValue(InitTy); 399 } else { 400 Init = EmitConstantExpr(D->getInit()); 401 } 402 const llvm::Type* InitType = Init->getType(); 403 404 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()]; 405 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry); 406 407 if (!GV) { 408 GV = new llvm::GlobalVariable(InitType, false, 409 llvm::GlobalValue::ExternalLinkage, 410 0, D->getName(), &getModule(), 0, 411 ASTTy.getAddressSpace()); 412 } else if (GV->getType() != 413 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) { 414 // We have a definition after a prototype with the wrong type. 415 // We must make a new GlobalVariable* and update everything that used OldGV 416 // (a declaration or tentative definition) with the new GlobalVariable* 417 // (which will be a definition). 418 // 419 // This happens if there is a prototype for a global (e.g. "extern int x[];") 420 // and then a definition of a different type (e.g. "int x[10];"). This also 421 // happens when an initializer has a different type from the type of the 422 // global (this happens with unions). 423 // 424 // FIXME: This also ends up happening if there's a definition followed by 425 // a tentative definition! (Although Sema rejects that construct 426 // at the moment.) 427 428 // Save the old global 429 llvm::GlobalVariable *OldGV = GV; 430 431 // Make a new global with the correct type 432 GV = new llvm::GlobalVariable(InitType, false, 433 llvm::GlobalValue::ExternalLinkage, 434 0, D->getName(), &getModule(), 0, 435 ASTTy.getAddressSpace()); 436 // Steal the name of the old global 437 GV->takeName(OldGV); 438 439 // Replace all uses of the old global with the new global 440 llvm::Constant *NewPtrForOldDecl = 441 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 442 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 443 444 // Erase the old global, since it is no longer used. 445 OldGV->eraseFromParent(); 446 } 447 448 Entry = GV; 449 450 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) { 451 SourceManager &SM = Context.getSourceManager(); 452 AddAnnotation(EmitAnnotateAttr(GV, AA, 453 SM.getLogicalLineNumber(D->getLocation()))); 454 } 455 456 GV->setInitializer(Init); 457 458 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays 459 unsigned Align; 460 if (const IncompleteArrayType* IAT = 461 Context.getAsIncompleteArrayType(D->getType())) 462 Align = Context.getTypeAlign(IAT->getElementType()); 463 else 464 Align = Context.getTypeAlign(D->getType()); 465 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) { 466 Align = std::max(Align, AA->getAlignment()); 467 } 468 GV->setAlignment(Align / 8); 469 470 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) 471 setGlobalVisibility(GV, attr->getVisibility()); 472 // FIXME: else handle -fvisibility 473 474 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) { 475 // Prefaced with special LLVM marker to indicate that the name 476 // should not be munged. 477 GV->setName("\01" + ALA->getLabel()); 478 } 479 480 // Set the llvm linkage type as appropriate. 481 if (D->getStorageClass() == VarDecl::Static) 482 GV->setLinkage(llvm::Function::InternalLinkage); 483 else if (D->getAttr<DLLImportAttr>()) 484 GV->setLinkage(llvm::Function::DLLImportLinkage); 485 else if (D->getAttr<DLLExportAttr>()) 486 GV->setLinkage(llvm::Function::DLLExportLinkage); 487 else if (D->getAttr<WeakAttr>()) 488 GV->setLinkage(llvm::GlobalVariable::WeakLinkage); 489 else { 490 // FIXME: This isn't right. This should handle common linkage and other 491 // stuff. 492 switch (D->getStorageClass()) { 493 case VarDecl::Static: assert(0 && "This case handled above"); 494 case VarDecl::Auto: 495 case VarDecl::Register: 496 assert(0 && "Can't have auto or register globals"); 497 case VarDecl::None: 498 if (!D->getInit()) 499 GV->setLinkage(llvm::GlobalVariable::CommonLinkage); 500 break; 501 case VarDecl::Extern: 502 case VarDecl::PrivateExtern: 503 // todo: common 504 break; 505 } 506 } 507 508 // Emit global variable debug information. 509 CGDebugInfo *DI = getDebugInfo(); 510 if(DI) { 511 if(D->getLocation().isValid()) 512 DI->setLocation(D->getLocation()); 513 DI->EmitGlobalVariable(GV, D); 514 } 515 } 516 517 llvm::GlobalValue * 518 CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) { 519 // FIXME: param attributes for sext/zext etc. 520 if (const AliasAttr *AA = D->getAttr<AliasAttr>()) { 521 assert(!D->getBody() && "Unexpected alias attr on function with body."); 522 523 const std::string& aliaseeName = AA->getAliasee(); 524 llvm::Function *aliasee = getModule().getFunction(aliaseeName); 525 llvm::GlobalValue *alias = new llvm::GlobalAlias(aliasee->getType(), 526 llvm::Function::ExternalLinkage, 527 D->getName(), 528 aliasee, 529 &getModule()); 530 SetGlobalValueAttributes(D, alias); 531 return alias; 532 } else { 533 const llvm::Type *Ty = getTypes().ConvertType(D->getType()); 534 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty); 535 llvm::Function *F = llvm::Function::Create(FTy, 536 llvm::Function::ExternalLinkage, 537 D->getName(), &getModule()); 538 539 SetFunctionAttributes(D, F, FTy); 540 return F; 541 } 542 } 543 544 llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) { 545 QualType ASTTy = D->getType(); 546 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy); 547 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace()); 548 549 // Lookup the entry, lazily creating it if necessary. 550 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()]; 551 if (!Entry) 552 Entry = EmitForwardFunctionDefinition(D); 553 554 return llvm::ConstantExpr::getBitCast(Entry, PTy); 555 } 556 557 void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) { 558 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()]; 559 if (!Entry) { 560 Entry = EmitForwardFunctionDefinition(D); 561 } else { 562 // If the types mismatch then we have to rewrite the definition. 563 const llvm::Type *Ty = getTypes().ConvertType(D->getType()); 564 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) { 565 // Otherwise, we have a definition after a prototype with the wrong type. 566 // F is the Function* for the one with the wrong type, we must make a new 567 // Function* and update everything that used F (a declaration) with the new 568 // Function* (which will be a definition). 569 // 570 // This happens if there is a prototype for a function (e.g. "int f()") and 571 // then a definition of a different type (e.g. "int f(int x)"). Start by 572 // making a new function of the correct type, RAUW, then steal the name. 573 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D); 574 NewFn->takeName(Entry); 575 576 // Replace uses of F with the Function we will endow with a body. 577 llvm::Constant *NewPtrForOldDecl = 578 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 579 Entry->replaceAllUsesWith(NewPtrForOldDecl); 580 581 // Ok, delete the old function now, which is dead. 582 // FIXME: Add GlobalValue->eraseFromParent(). 583 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration"); 584 if (llvm::Function *F = dyn_cast<llvm::Function>(Entry)) { 585 F->eraseFromParent(); 586 } else if (llvm::GlobalAlias *GA = dyn_cast<llvm::GlobalAlias>(Entry)) { 587 GA->eraseFromParent(); 588 } else { 589 assert(0 && "Invalid global variable type."); 590 } 591 592 Entry = NewFn; 593 } 594 } 595 596 if (D->getAttr<AliasAttr>()) { 597 ; 598 } else { 599 llvm::Function *Fn = cast<llvm::Function>(Entry); 600 CodeGenFunction(*this).GenerateCode(D, Fn); 601 602 // Set attributes specific to definition. 603 // FIXME: This needs to be cleaned up by clearly emitting the 604 // declaration / definition at separate times. 605 if (!Features.Exceptions) 606 Fn->addParamAttr(0, llvm::ParamAttr::NoUnwind); 607 608 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) { 609 AddGlobalCtor(Fn, CA->getPriority()); 610 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) { 611 AddGlobalDtor(Fn, DA->getPriority()); 612 } 613 } 614 } 615 616 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 617 // Make sure that this type is translated. 618 Types.UpdateCompletedType(TD); 619 } 620 621 622 /// getBuiltinLibFunction 623 llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) { 624 if (BuiltinID > BuiltinFunctions.size()) 625 BuiltinFunctions.resize(BuiltinID); 626 627 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve 628 // a slot for it. 629 assert(BuiltinID && "Invalid Builtin ID"); 630 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1]; 631 if (FunctionSlot) 632 return FunctionSlot; 633 634 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn"); 635 636 // Get the name, skip over the __builtin_ prefix. 637 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10; 638 639 // Get the type for the builtin. 640 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context); 641 const llvm::FunctionType *Ty = 642 cast<llvm::FunctionType>(getTypes().ConvertType(Type)); 643 644 // FIXME: This has a serious problem with code like this: 645 // void abs() {} 646 // ... __builtin_abs(x); 647 // The two versions of abs will collide. The fix is for the builtin to win, 648 // and for the existing one to be turned into a constantexpr cast of the 649 // builtin. In the case where the existing one is a static function, it 650 // should just be renamed. 651 if (llvm::Function *Existing = getModule().getFunction(Name)) { 652 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage()) 653 return FunctionSlot = Existing; 654 assert(Existing == 0 && "FIXME: Name collision"); 655 } 656 657 // FIXME: param attributes for sext/zext etc. 658 return FunctionSlot = 659 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name, 660 &getModule()); 661 } 662 663 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys, 664 unsigned NumTys) { 665 return llvm::Intrinsic::getDeclaration(&getModule(), 666 (llvm::Intrinsic::ID)IID, Tys, NumTys); 667 } 668 669 llvm::Function *CodeGenModule::getMemCpyFn() { 670 if (MemCpyFn) return MemCpyFn; 671 llvm::Intrinsic::ID IID; 672 switch (Context.Target.getPointerWidth(0)) { 673 default: assert(0 && "Unknown ptr width"); 674 case 32: IID = llvm::Intrinsic::memcpy_i32; break; 675 case 64: IID = llvm::Intrinsic::memcpy_i64; break; 676 } 677 return MemCpyFn = getIntrinsic(IID); 678 } 679 680 llvm::Function *CodeGenModule::getMemMoveFn() { 681 if (MemMoveFn) return MemMoveFn; 682 llvm::Intrinsic::ID IID; 683 switch (Context.Target.getPointerWidth(0)) { 684 default: assert(0 && "Unknown ptr width"); 685 case 32: IID = llvm::Intrinsic::memmove_i32; break; 686 case 64: IID = llvm::Intrinsic::memmove_i64; break; 687 } 688 return MemMoveFn = getIntrinsic(IID); 689 } 690 691 llvm::Function *CodeGenModule::getMemSetFn() { 692 if (MemSetFn) return MemSetFn; 693 llvm::Intrinsic::ID IID; 694 switch (Context.Target.getPointerWidth(0)) { 695 default: assert(0 && "Unknown ptr width"); 696 case 32: IID = llvm::Intrinsic::memset_i32; break; 697 case 64: IID = llvm::Intrinsic::memset_i64; break; 698 } 699 return MemSetFn = getIntrinsic(IID); 700 } 701 702 // FIXME: This needs moving into an Apple Objective-C runtime class 703 llvm::Constant *CodeGenModule:: 704 GetAddrOfConstantCFString(const std::string &str) { 705 llvm::StringMapEntry<llvm::Constant *> &Entry = 706 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 707 708 if (Entry.getValue()) 709 return Entry.getValue(); 710 711 std::vector<llvm::Constant*> Fields; 712 713 if (!CFConstantStringClassRef) { 714 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 715 Ty = llvm::ArrayType::get(Ty, 0); 716 717 CFConstantStringClassRef = 718 new llvm::GlobalVariable(Ty, false, 719 llvm::GlobalVariable::ExternalLinkage, 0, 720 "__CFConstantStringClassReference", 721 &getModule()); 722 } 723 724 // Class pointer. 725 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty); 726 llvm::Constant *Zeros[] = { Zero, Zero }; 727 llvm::Constant *C = 728 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2); 729 Fields.push_back(C); 730 731 // Flags. 732 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 733 Fields.push_back(llvm::ConstantInt::get(Ty, 1992)); 734 735 // String pointer. 736 C = llvm::ConstantArray::get(str); 737 C = new llvm::GlobalVariable(C->getType(), true, 738 llvm::GlobalValue::InternalLinkage, 739 C, ".str", &getModule()); 740 741 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2); 742 Fields.push_back(C); 743 744 // String length. 745 Ty = getTypes().ConvertType(getContext().LongTy); 746 Fields.push_back(llvm::ConstantInt::get(Ty, str.length())); 747 748 // The struct. 749 Ty = getTypes().ConvertType(getContext().getCFConstantStringType()); 750 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields); 751 llvm::GlobalVariable *GV = 752 new llvm::GlobalVariable(C->getType(), true, 753 llvm::GlobalVariable::InternalLinkage, 754 C, "", &getModule()); 755 GV->setSection("__DATA,__cfstring"); 756 Entry.setValue(GV); 757 return GV; 758 } 759 760 /// GetStringForStringLiteral - Return the appropriate bytes for a 761 /// string literal, properly padded to match the literal type. 762 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) { 763 assert(!E->isWide() && "FIXME: Wide strings not supported yet!"); 764 const char *StrData = E->getStrData(); 765 unsigned Len = E->getByteLength(); 766 767 const ConstantArrayType *CAT = 768 getContext().getAsConstantArrayType(E->getType()); 769 assert(CAT && "String isn't pointer or array!"); 770 771 // Resize the string to the right size 772 // FIXME: What about wchar_t strings? 773 std::string Str(StrData, StrData+Len); 774 uint64_t RealLen = CAT->getSize().getZExtValue(); 775 Str.resize(RealLen, '\0'); 776 777 return Str; 778 } 779 780 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 781 /// constant array for the given string literal. 782 llvm::Constant * 783 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 784 // FIXME: This can be more efficient. 785 return GetAddrOfConstantString(GetStringForStringLiteral(S)); 786 } 787 788 /// GenerateWritableString -- Creates storage for a string literal. 789 static llvm::Constant *GenerateStringLiteral(const std::string &str, 790 bool constant, 791 CodeGenModule &CGM) { 792 // Create Constant for this string literal. Don't add a '\0'. 793 llvm::Constant *C = llvm::ConstantArray::get(str, false); 794 795 // Create a global variable for this string 796 C = new llvm::GlobalVariable(C->getType(), constant, 797 llvm::GlobalValue::InternalLinkage, 798 C, ".str", &CGM.getModule()); 799 800 return C; 801 } 802 803 /// GetAddrOfConstantString - Returns a pointer to a character array 804 /// containing the literal. This contents are exactly that of the 805 /// given string, i.e. it will not be null terminated automatically; 806 /// see GetAddrOfConstantCString. Note that whether the result is 807 /// actually a pointer to an LLVM constant depends on 808 /// Feature.WriteableStrings. 809 /// 810 /// The result has pointer to array type. 811 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) { 812 // Don't share any string literals if writable-strings is turned on. 813 if (Features.WritableStrings) 814 return GenerateStringLiteral(str, false, *this); 815 816 llvm::StringMapEntry<llvm::Constant *> &Entry = 817 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 818 819 if (Entry.getValue()) 820 return Entry.getValue(); 821 822 // Create a global variable for this. 823 llvm::Constant *C = GenerateStringLiteral(str, true, *this); 824 Entry.setValue(C); 825 return C; 826 } 827 828 /// GetAddrOfConstantCString - Returns a pointer to a character 829 /// array containing the literal and a terminating '\-' 830 /// character. The result has pointer to array type. 831 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str) { 832 return GetAddrOfConstantString(str + "\0"); 833 } 834 835 /// EmitTopLevelDecl - Emit code for a single top level declaration. 836 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 837 // If an error has occurred, stop code generation, but continue 838 // parsing and semantic analysis (to ensure all warnings and errors 839 // are emitted). 840 if (Diags.hasErrorOccurred()) 841 return; 842 843 switch (D->getKind()) { 844 case Decl::Function: 845 case Decl::Var: 846 EmitGlobal(cast<ValueDecl>(D)); 847 break; 848 849 case Decl::Namespace: 850 assert(0 && "FIXME: Namespace unsupported"); 851 break; 852 853 // Objective-C Decls 854 855 // Forward declarations, no (immediate) code generation. 856 case Decl::ObjCClass: 857 case Decl::ObjCCategory: 858 case Decl::ObjCForwardProtocol: 859 case Decl::ObjCInterface: 860 break; 861 862 case Decl::ObjCProtocol: 863 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D)); 864 break; 865 866 case Decl::ObjCCategoryImpl: 867 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 868 break; 869 870 case Decl::ObjCImplementation: 871 Runtime->GenerateClass(cast<ObjCImplementationDecl>(D)); 872 break; 873 874 case Decl::ObjCMethod: { 875 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 876 // If this is not a prototype, emit the body. 877 if (OMD->getBody()) 878 CodeGenFunction(*this).GenerateObjCMethod(OMD); 879 break; 880 } 881 case Decl::ObjCPropertyImpl: 882 assert(0 && "FIXME: ObjCPropertyImpl unsupported"); 883 break; 884 case Decl::ObjCCompatibleAlias: 885 assert(0 && "FIXME: ObjCCompatibleAlias unsupported"); 886 break; 887 888 case Decl::LinkageSpec: { 889 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D); 890 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx) 891 WarnUnsupported(LSD, "linkage spec"); 892 // FIXME: implement C++ linkage, C linkage works mostly by C 893 // language reuse already. 894 break; 895 } 896 897 case Decl::FileScopeAsm: { 898 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 899 std::string AsmString(AD->getAsmString()->getStrData(), 900 AD->getAsmString()->getByteLength()); 901 902 const std::string &S = getModule().getModuleInlineAsm(); 903 if (S.empty()) 904 getModule().setModuleInlineAsm(AsmString); 905 else 906 getModule().setModuleInlineAsm(S + '\n' + AsmString); 907 break; 908 } 909 910 default: 911 // Make sure we handled everything we should, every other kind is 912 // a non-top-level decl. FIXME: Would be nice to have an 913 // isTopLevelDeclKind function. Need to recode Decl::Kind to do 914 // that easily. 915 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 916 } 917 } 918 919