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 "CodeGenFunction.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/Decl.h" 18 #include "clang/Basic/Diagnostic.h" 19 #include "clang/Basic/LangOptions.h" 20 #include "clang/Basic/TargetInfo.h" 21 #include "llvm/CallingConv.h" 22 #include "llvm/Constants.h" 23 #include "llvm/DerivedTypes.h" 24 #include "llvm/Module.h" 25 #include "llvm/Intrinsics.h" 26 #include <algorithm> 27 using namespace clang; 28 using namespace CodeGen; 29 30 31 CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO, 32 llvm::Module &M, const llvm::TargetData &TD, 33 Diagnostic &diags) 34 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags), 35 Types(C, M, TD), MemCpyFn(0), MemSetFn(0), CFConstantStringClassRef(0) { 36 //TODO: Make this selectable at runtime 37 Runtime = CreateObjCRuntime(M); 38 } 39 40 CodeGenModule::~CodeGenModule() { 41 EmitGlobalCtors(); 42 delete Runtime; 43 } 44 45 /// WarnUnsupported - Print out a warning that codegen doesn't support the 46 /// specified stmt yet. 47 void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) { 48 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning, 49 "cannot codegen this %0 yet"); 50 SourceRange Range = S->getSourceRange(); 51 std::string Msg = Type; 52 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID, 53 &Msg, 1, &Range, 1); 54 } 55 56 /// WarnUnsupported - Print out a warning that codegen doesn't support the 57 /// specified decl yet. 58 void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) { 59 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning, 60 "cannot codegen this %0 yet"); 61 std::string Msg = Type; 62 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID, 63 &Msg, 1); 64 } 65 66 /// AddGlobalCtor - Add a function to the list that will be called before 67 /// main() runs. 68 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor) { 69 // TODO: Type coercion of void()* types. 70 GlobalCtors.push_back(Ctor); 71 } 72 73 void CodeGenModule::EmitGlobalCtors() { 74 // Get the type of @llvm.global_ctors 75 std::vector<const llvm::Type*> CtorFields; 76 CtorFields.push_back(llvm::IntegerType::get(32)); 77 // Constructor function type 78 std::vector<const llvm::Type*> VoidArgs; 79 llvm::FunctionType* CtorFuncTy = llvm::FunctionType::get( 80 llvm::Type::VoidTy, 81 VoidArgs, 82 false); 83 // i32, function type pair 84 CtorFields.push_back(llvm::PointerType::getUnqual(CtorFuncTy)); 85 llvm::StructType* CtorStructTy = llvm::StructType::get(CtorFields, false); 86 // Array of fields 87 llvm::ArrayType* GlobalCtorsTy = llvm::ArrayType::get(CtorStructTy, 88 GlobalCtors.size()); 89 90 const std::string GlobalCtorsVar = std::string("llvm.global_ctors"); 91 // Define the global variable 92 llvm::GlobalVariable *GlobalCtorsVal = new llvm::GlobalVariable( 93 GlobalCtorsTy, 94 false, 95 llvm::GlobalValue::AppendingLinkage, 96 (llvm::Constant*)0, 97 GlobalCtorsVar, 98 &TheModule); 99 100 // Populate the array 101 std::vector<llvm::Constant*> CtorValues; 102 llvm::Constant *MagicNumber = llvm::ConstantInt::get(llvm::IntegerType::Int32Ty, 103 65535, 104 false); 105 for (std::vector<llvm::Constant*>::iterator I = GlobalCtors.begin(), 106 E = GlobalCtors.end(); I != E; ++I) { 107 std::vector<llvm::Constant*> StructValues; 108 StructValues.push_back(MagicNumber); 109 StructValues.push_back(*I); 110 111 llvm::Constant* CtorEntry = llvm::ConstantStruct::get(CtorStructTy, StructValues); 112 CtorValues.push_back(CtorEntry); 113 } 114 llvm::Constant* CtorArray = llvm::ConstantArray::get(GlobalCtorsTy, CtorValues); 115 GlobalCtorsVal->setInitializer(CtorArray); 116 117 } 118 119 /// ReplaceMapValuesWith - This is a really slow and bad function that 120 /// searches for any entries in GlobalDeclMap that point to OldVal, changing 121 /// them to point to NewVal. This is badbadbad, FIXME! 122 void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal, 123 llvm::Constant *NewVal) { 124 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator 125 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I) 126 if (I->second == OldVal) I->second = NewVal; 127 } 128 129 130 llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D, 131 bool isDefinition) { 132 // See if it is already in the map. If so, just return it. 133 llvm::Constant *&Entry = GlobalDeclMap[D]; 134 if (Entry) return Entry; 135 136 const llvm::Type *Ty = getTypes().ConvertType(D->getType()); 137 138 // Check to see if the function already exists. 139 llvm::Function *F = getModule().getFunction(D->getName()); 140 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty); 141 142 // If it doesn't already exist, just create and return an entry. 143 if (F == 0) { 144 // FIXME: param attributes for sext/zext etc. 145 F = new llvm::Function(FTy, llvm::Function::ExternalLinkage, D->getName(), 146 &getModule()); 147 148 // Set the appropriate calling convention for the Function. 149 if (D->getAttr<FastCallAttr>()) 150 F->setCallingConv(llvm::CallingConv::Fast); 151 return Entry = F; 152 } 153 154 // If the pointer type matches, just return it. 155 llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty); 156 if (PFTy == F->getType()) return Entry = F; 157 158 // If this isn't a definition, just return it casted to the right type. 159 if (!isDefinition) 160 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy); 161 162 // Otherwise, we have a definition after a prototype with the wrong type. 163 // F is the Function* for the one with the wrong type, we must make a new 164 // Function* and update everything that used F (a declaration) with the new 165 // Function* (which will be a definition). 166 // 167 // This happens if there is a prototype for a function (e.g. "int f()") and 168 // then a definition of a different type (e.g. "int f(int x)"). Start by 169 // making a new function of the correct type, RAUW, then steal the name. 170 llvm::Function *NewFn = new llvm::Function(FTy, 171 llvm::Function::ExternalLinkage, 172 "", &getModule()); 173 NewFn->takeName(F); 174 175 // Replace uses of F with the Function we will endow with a body. 176 llvm::Constant *NewPtrForOldDecl = 177 llvm::ConstantExpr::getBitCast(NewFn, F->getType()); 178 F->replaceAllUsesWith(NewPtrForOldDecl); 179 180 // FIXME: Update the globaldeclmap for the previous decl of this name. We 181 // really want a way to walk all of these, but we don't have it yet. This 182 // is incredibly slow! 183 ReplaceMapValuesWith(F, NewPtrForOldDecl); 184 185 // Ok, delete the old function now, which is dead. 186 assert(F->isDeclaration() && "Shouldn't replace non-declaration"); 187 F->eraseFromParent(); 188 189 // Return the new function which has the right type. 190 return Entry = NewFn; 191 } 192 193 static bool IsZeroElementArray(const llvm::Type *Ty) { 194 if (const llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(Ty)) 195 return ATy->getNumElements() == 0; 196 return false; 197 } 198 199 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 200 bool isDefinition) { 201 assert(D->hasGlobalStorage() && "Not a global variable"); 202 203 // See if it is already in the map. 204 llvm::Constant *&Entry = GlobalDeclMap[D]; 205 if (Entry) return Entry; 206 207 QualType ASTTy = D->getType(); 208 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy); 209 210 // Check to see if the global already exists. 211 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true); 212 213 // If it doesn't already exist, just create and return an entry. 214 if (GV == 0) { 215 return Entry = new llvm::GlobalVariable(Ty, false, 216 llvm::GlobalValue::ExternalLinkage, 217 0, D->getName(), &getModule(), 0, 218 ASTTy.getAddressSpace()); 219 } 220 221 // If the pointer type matches, just return it. 222 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 223 if (PTy == GV->getType()) return Entry = GV; 224 225 // If this isn't a definition, just return it casted to the right type. 226 if (!isDefinition) 227 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy); 228 229 230 // Otherwise, we have a definition after a prototype with the wrong type. 231 // GV is the GlobalVariable* for the one with the wrong type, we must make a 232 /// new GlobalVariable* and update everything that used GV (a declaration) 233 // with the new GlobalVariable* (which will be a definition). 234 // 235 // This happens if there is a prototype for a global (e.g. "extern int x[];") 236 // and then a definition of a different type (e.g. "int x[10];"). Start by 237 // making a new global of the correct type, RAUW, then steal the name. 238 llvm::GlobalVariable *NewGV = 239 new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage, 240 0, D->getName(), &getModule(), 0, 241 ASTTy.getAddressSpace()); 242 NewGV->takeName(GV); 243 244 // Replace uses of GV with the globalvalue we will endow with a body. 245 llvm::Constant *NewPtrForOldDecl = 246 llvm::ConstantExpr::getBitCast(NewGV, GV->getType()); 247 GV->replaceAllUsesWith(NewPtrForOldDecl); 248 249 // FIXME: Update the globaldeclmap for the previous decl of this name. We 250 // really want a way to walk all of these, but we don't have it yet. This 251 // is incredibly slow! 252 ReplaceMapValuesWith(GV, NewPtrForOldDecl); 253 254 // Verify that GV was a declaration or something like x[] which turns into 255 // [0 x type]. 256 assert((GV->isDeclaration() || 257 IsZeroElementArray(GV->getType()->getElementType())) && 258 "Shouldn't replace non-declaration"); 259 260 // Ok, delete the old global now, which is dead. 261 GV->eraseFromParent(); 262 263 // Return the new global which has the right type. 264 return Entry = NewGV; 265 } 266 267 268 void CodeGenModule::EmitFunction(const FunctionDecl *FD) { 269 // If this is not a prototype, emit the body. 270 if (FD->getBody()) 271 CodeGenFunction(*this).GenerateCode(FD); 272 } 273 274 llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expr) { 275 return EmitConstantExpr(Expr); 276 } 277 278 void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) { 279 // If this is just a forward declaration of the variable, don't emit it now, 280 // allow it to be emitted lazily on its first use. 281 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0) 282 return; 283 284 // Get the global, forcing it to be a direct reference. 285 llvm::GlobalVariable *GV = 286 cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, true)); 287 288 // Convert the initializer, or use zero if appropriate. 289 llvm::Constant *Init = 0; 290 if (D->getInit() == 0) { 291 Init = llvm::Constant::getNullValue(GV->getType()->getElementType()); 292 } else if (D->getType()->isIntegerType()) { 293 llvm::APSInt Value(static_cast<uint32_t>( 294 getContext().getTypeSize(D->getInit()->getType()))); 295 if (D->getInit()->isIntegerConstantExpr(Value, Context)) 296 Init = llvm::ConstantInt::get(Value); 297 } 298 299 if (!Init) 300 Init = EmitGlobalInit(D->getInit()); 301 302 assert(GV->getType()->getElementType() == Init->getType() && 303 "Initializer codegen type mismatch!"); 304 GV->setInitializer(Init); 305 306 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) 307 GV->setVisibility(attr->getVisibility()); 308 // FIXME: else handle -fvisibility 309 310 // Set the llvm linkage type as appropriate. 311 if (D->getAttr<DLLImportAttr>()) 312 GV->setLinkage(llvm::Function::DLLImportLinkage); 313 else if (D->getAttr<DLLExportAttr>()) 314 GV->setLinkage(llvm::Function::DLLExportLinkage); 315 else if (D->getAttr<WeakAttr>()) { 316 GV->setLinkage(llvm::GlobalVariable::WeakLinkage); 317 318 } else { 319 // FIXME: This isn't right. This should handle common linkage and other 320 // stuff. 321 switch (D->getStorageClass()) { 322 case VarDecl::Auto: 323 case VarDecl::Register: 324 assert(0 && "Can't have auto or register globals"); 325 case VarDecl::None: 326 if (!D->getInit()) 327 GV->setLinkage(llvm::GlobalVariable::WeakLinkage); 328 break; 329 case VarDecl::Extern: 330 case VarDecl::PrivateExtern: 331 // todo: common 332 break; 333 case VarDecl::Static: 334 GV->setLinkage(llvm::GlobalVariable::InternalLinkage); 335 break; 336 } 337 } 338 } 339 340 /// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified 341 /// declarator chain. 342 void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) { 343 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator())) 344 EmitGlobalVar(D); 345 } 346 347 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 348 // Make sure that this type is translated. 349 Types.UpdateCompletedType(TD); 350 } 351 352 353 /// getBuiltinLibFunction 354 llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) { 355 if (BuiltinID > BuiltinFunctions.size()) 356 BuiltinFunctions.resize(BuiltinID); 357 358 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve 359 // a slot for it. 360 assert(BuiltinID && "Invalid Builtin ID"); 361 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1]; 362 if (FunctionSlot) 363 return FunctionSlot; 364 365 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn"); 366 367 // Get the name, skip over the __builtin_ prefix. 368 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10; 369 370 // Get the type for the builtin. 371 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context); 372 const llvm::FunctionType *Ty = 373 cast<llvm::FunctionType>(getTypes().ConvertType(Type)); 374 375 // FIXME: This has a serious problem with code like this: 376 // void abs() {} 377 // ... __builtin_abs(x); 378 // The two versions of abs will collide. The fix is for the builtin to win, 379 // and for the existing one to be turned into a constantexpr cast of the 380 // builtin. In the case where the existing one is a static function, it 381 // should just be renamed. 382 if (llvm::Function *Existing = getModule().getFunction(Name)) { 383 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage()) 384 return FunctionSlot = Existing; 385 assert(Existing == 0 && "FIXME: Name collision"); 386 } 387 388 // FIXME: param attributes for sext/zext etc. 389 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage, 390 Name, &getModule()); 391 } 392 393 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys, 394 unsigned NumTys) { 395 return llvm::Intrinsic::getDeclaration(&getModule(), 396 (llvm::Intrinsic::ID)IID, Tys, NumTys); 397 } 398 399 llvm::Function *CodeGenModule::getMemCpyFn() { 400 if (MemCpyFn) return MemCpyFn; 401 llvm::Intrinsic::ID IID; 402 switch (Context.Target.getPointerWidth(0)) { 403 default: assert(0 && "Unknown ptr width"); 404 case 32: IID = llvm::Intrinsic::memcpy_i32; break; 405 case 64: IID = llvm::Intrinsic::memcpy_i64; break; 406 } 407 return MemCpyFn = getIntrinsic(IID); 408 } 409 410 llvm::Function *CodeGenModule::getMemSetFn() { 411 if (MemSetFn) return MemSetFn; 412 llvm::Intrinsic::ID IID; 413 switch (Context.Target.getPointerWidth(0)) { 414 default: assert(0 && "Unknown ptr width"); 415 case 32: IID = llvm::Intrinsic::memset_i32; break; 416 case 64: IID = llvm::Intrinsic::memset_i64; break; 417 } 418 return MemSetFn = getIntrinsic(IID); 419 } 420 421 llvm::Constant *CodeGenModule:: 422 GetAddrOfConstantCFString(const std::string &str) { 423 llvm::StringMapEntry<llvm::Constant *> &Entry = 424 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 425 426 if (Entry.getValue()) 427 return Entry.getValue(); 428 429 std::vector<llvm::Constant*> Fields; 430 431 if (!CFConstantStringClassRef) { 432 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 433 Ty = llvm::ArrayType::get(Ty, 0); 434 435 CFConstantStringClassRef = 436 new llvm::GlobalVariable(Ty, false, 437 llvm::GlobalVariable::ExternalLinkage, 0, 438 "__CFConstantStringClassReference", 439 &getModule()); 440 } 441 442 // Class pointer. 443 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty); 444 llvm::Constant *Zeros[] = { Zero, Zero }; 445 llvm::Constant *C = 446 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2); 447 Fields.push_back(C); 448 449 // Flags. 450 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 451 Fields.push_back(llvm::ConstantInt::get(Ty, 1992)); 452 453 // String pointer. 454 C = llvm::ConstantArray::get(str); 455 C = new llvm::GlobalVariable(C->getType(), true, 456 llvm::GlobalValue::InternalLinkage, 457 C, ".str", &getModule()); 458 459 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2); 460 Fields.push_back(C); 461 462 // String length. 463 Ty = getTypes().ConvertType(getContext().LongTy); 464 Fields.push_back(llvm::ConstantInt::get(Ty, str.length())); 465 466 // The struct. 467 Ty = getTypes().ConvertType(getContext().getCFConstantStringType()); 468 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields); 469 llvm::GlobalVariable *GV = 470 new llvm::GlobalVariable(C->getType(), true, 471 llvm::GlobalVariable::InternalLinkage, 472 C, "", &getModule()); 473 GV->setSection("__DATA,__cfstring"); 474 Entry.setValue(GV); 475 return GV; 476 } 477 478 /// GenerateWritableString -- Creates storage for a string literal. 479 static llvm::Constant *GenerateStringLiteral(const std::string &str, 480 bool constant, 481 CodeGenModule &CGM) { 482 // Create Constant for this string literal 483 llvm::Constant *C=llvm::ConstantArray::get(str); 484 485 // Create a global variable for this string 486 C = new llvm::GlobalVariable(C->getType(), constant, 487 llvm::GlobalValue::InternalLinkage, 488 C, ".str", &CGM.getModule()); 489 return C; 490 } 491 492 /// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character 493 /// array containing the literal. The result is pointer to array type. 494 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) { 495 // Don't share any string literals if writable-strings is turned on. 496 if (Features.WritableStrings) 497 return GenerateStringLiteral(str, false, *this); 498 499 llvm::StringMapEntry<llvm::Constant *> &Entry = 500 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 501 502 if (Entry.getValue()) 503 return Entry.getValue(); 504 505 // Create a global variable for this. 506 llvm::Constant *C = GenerateStringLiteral(str, true, *this); 507 Entry.setValue(C); 508 return C; 509 } 510