function.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/sem_ir/function.h"
  5. #include "toolchain/sem_ir/file.h"
  6. #include "toolchain/sem_ir/generic.h"
  7. #include "toolchain/sem_ir/ids.h"
  8. namespace Carbon::SemIR {
  9. auto GetCalleeFunction(const File& sem_ir, InstId callee_id) -> CalleeFunction {
  10. CalleeFunction result = {.function_id = FunctionId::Invalid,
  11. .specific_id = SpecificId::Invalid,
  12. .self_id = InstId::Invalid,
  13. .is_error = false};
  14. if (auto bound_method = sem_ir.insts().TryGetAs<BoundMethod>(callee_id)) {
  15. result.self_id = bound_method->object_id;
  16. callee_id = bound_method->function_id;
  17. }
  18. // Identify the function we're calling.
  19. auto val_id = sem_ir.constant_values().GetConstantInstId(callee_id);
  20. if (!val_id.is_valid()) {
  21. return result;
  22. }
  23. auto val_inst = sem_ir.insts().Get(val_id);
  24. auto struct_val = val_inst.TryAs<StructValue>();
  25. if (!struct_val) {
  26. result.is_error = val_inst.type_id() == SemIR::TypeId::Error;
  27. return result;
  28. }
  29. auto fn_type = sem_ir.types().TryGetAs<FunctionType>(struct_val->type_id);
  30. if (!fn_type) {
  31. return result;
  32. }
  33. result.function_id = fn_type->function_id;
  34. result.specific_id = fn_type->specific_id;
  35. return result;
  36. }
  37. auto Function::GetParamFromParamRefId(const File& sem_ir, InstId param_ref_id)
  38. -> std::pair<InstId, Param> {
  39. auto ref = sem_ir.insts().Get(param_ref_id);
  40. if (auto addr_pattern = ref.TryAs<SemIR::AddrPattern>()) {
  41. param_ref_id = addr_pattern->inner_id;
  42. ref = sem_ir.insts().Get(param_ref_id);
  43. }
  44. if (auto bind_name = ref.TryAs<SemIR::AnyBindName>()) {
  45. param_ref_id = bind_name->value_id;
  46. ref = sem_ir.insts().Get(param_ref_id);
  47. }
  48. return {param_ref_id, ref.As<SemIR::Param>()};
  49. }
  50. auto Function::GetDeclaredReturnType(const File& file,
  51. SpecificId specific_id) const -> TypeId {
  52. if (!return_storage_id.is_valid()) {
  53. return TypeId::Invalid;
  54. }
  55. return GetTypeInSpecific(file, specific_id,
  56. file.insts().Get(return_storage_id).type_id());
  57. }
  58. } // namespace Carbon::SemIR